Skip to content

Commit 63d1002

Browse files
committed
update documentation
1 parent 320e376 commit 63d1002

File tree

4 files changed

+668
-3
lines changed

4 files changed

+668
-3
lines changed

docs/api/orderbook.rst

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,11 @@ Institutional Features
9999
.. automethod:: OrderBook.detect_iceberg_orders_advanced
100100
.. automethod:: OrderBook.get_support_resistance_levels
101101

102+
Market Manipulation Detection
103+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
104+
105+
.. automethod:: OrderBook.detect_spoofing
106+
102107
Comprehensive Analysis
103108
~~~~~~~~~~~~~~~~~~~~~~
104109

@@ -228,6 +233,124 @@ Support and Resistance Analysis
228233
for level in levels['resistance_levels'][:3]: # Top 3 resistance levels
229234
print(f"${level['price']:.2f} - Strength: {level['strength']:.2f} - Volume: {level['volume']}")
230235
236+
Spoofing Detection (v3.3.4+)
237+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
238+
239+
**NEW in v3.3.4**: Comprehensive market manipulation detection with 6 pattern types.
240+
241+
The OrderBook now includes sophisticated spoofing detection algorithms that identify common market manipulation patterns:
242+
243+
**Detection Patterns:**
244+
245+
1. **Layering**: Multiple orders at different price levels with high cancellation rates
246+
2. **Quote Stuffing**: Rapid placement and cancellation of orders to create noise
247+
3. **Momentum Ignition**: Aggressive orders designed to trigger other participants
248+
4. **Flashing**: Brief display of large orders to mislead other traders
249+
5. **Wash Trading**: Self-trading to create artificial volume
250+
6. **Basic Spoofing**: General patterns with high cancellation rates
251+
252+
.. code-block:: python
253+
254+
async def detect_market_manipulation():
255+
# Using TradingSuite with orderbook
256+
suite = await TradingSuite.create("ES", features=["orderbook"])
257+
258+
# Basic spoofing detection with default parameters
259+
spoofing = await suite.orderbook.detect_spoofing()
260+
261+
print("=== Spoofing Detection Results ===")
262+
for detection in spoofing:
263+
print(f"Pattern: {detection['pattern']}")
264+
print(f"Price: ${detection['price']:.2f}")
265+
print(f"Side: {detection['side']}")
266+
print(f"Confidence: {detection['confidence']:.1%}")
267+
print(f"Cancellation Rate: {detection['cancellation_rate']:.1%}")
268+
print(f"Frequency: {detection['placement_frequency']:.1f}/min")
269+
print(f"Distance from Market: {detection['distance_from_market']} ticks")
270+
print("---")
271+
272+
await suite.disconnect()
273+
274+
.. code-block:: python
275+
276+
async def advanced_spoofing_detection():
277+
suite = await TradingSuite.create("MNQ", features=["orderbook"])
278+
279+
# Custom parameters for more sensitive detection
280+
spoofing = await suite.orderbook.detect_spoofing(
281+
time_window_minutes=5, # Shorter analysis window
282+
min_placement_frequency=5.0, # Higher frequency threshold
283+
min_cancellation_rate=0.6, # Lower cancellation rate threshold
284+
max_time_to_cancel=15.0, # Faster cancellation requirement
285+
min_distance_ticks=2, # Closer to market
286+
confidence_threshold=0.5 # Lower confidence threshold
287+
)
288+
289+
# Analyze results by pattern type
290+
patterns = {}
291+
for detection in spoofing:
292+
pattern = detection['pattern']
293+
if pattern not in patterns:
294+
patterns[pattern] = []
295+
patterns[pattern].append(detection)
296+
297+
for pattern, detections in patterns.items():
298+
print(f"\n=== {pattern.upper()} PATTERN ===")
299+
print(f"Instances: {len(detections)}")
300+
avg_confidence = sum(d['confidence'] for d in detections) / len(detections)
301+
print(f"Average Confidence: {avg_confidence:.1%}")
302+
303+
# Show highest confidence detection
304+
best = max(detections, key=lambda x: x['confidence'])
305+
print(f"Best Detection: ${best['price']:.2f} ({best['confidence']:.1%})")
306+
307+
await suite.disconnect()
308+
309+
**Performance Optimizations (v3.3.4):**
310+
311+
- **80% Faster Detection**: Optimized from O(N²) to O(N log N) complexity
312+
- **Memory Bounded**: Maximum 1000 price levels tracked to prevent memory exhaustion
313+
- **Binary Search**: Efficient timestamp filtering for large order histories
314+
- **Configurable Tick Sizes**: Dynamic tick size detection via instrument API
315+
316+
**Regulatory Compliance Features:**
317+
318+
- **Pattern Classification**: Specific categorization for compliance reporting
319+
- **Confidence Scoring**: Quantified reliability for regulatory thresholds
320+
- **Historical Tracking**: Complete audit trail of detection events
321+
- **Timestamp Precision**: ISO format timestamps for regulatory requirements
322+
323+
.. code-block:: python
324+
325+
async def compliance_monitoring():
326+
"""Example for regulatory compliance monitoring."""
327+
suite = await TradingSuite.create("ES", features=["orderbook"])
328+
329+
# Continuous monitoring for compliance
330+
while True:
331+
# Detect spoofing with regulatory parameters
332+
spoofing = await suite.orderbook.detect_spoofing(
333+
confidence_threshold=0.8, # High confidence for compliance
334+
min_cancellation_rate=0.9, # Very high cancellation rate
335+
time_window_minutes=15 # Regulatory time window
336+
)
337+
338+
# Report high-confidence detections
339+
for detection in spoofing:
340+
if detection['confidence'] > 0.9:
341+
print(f"🚨 HIGH CONFIDENCE SPOOFING DETECTED")
342+
print(f"Time: {detection['first_detected']}")
343+
print(f"Pattern: {detection['pattern']}")
344+
print(f"Price: ${detection['price']:.2f}")
345+
print(f"Confidence: {detection['confidence']:.1%}")
346+
347+
# Log for compliance system
348+
# await log_to_compliance_system(detection)
349+
350+
await asyncio.sleep(60) # Check every minute
351+
352+
await suite.disconnect()
353+
231354
Real-time Integration
232355
~~~~~~~~~~~~~~~~~~~~
233356

@@ -409,6 +532,32 @@ The ``get_volume_profile()`` method returns:
409532
}
410533
}
411534
535+
Spoofing Detection Data
536+
~~~~~~~~~~~~~~~~~~~~~~~
537+
538+
The ``detect_spoofing()`` method returns a list of ``SpoofingDetectionResponse`` objects:
539+
540+
.. code-block:: python
541+
542+
[
543+
{
544+
"price": float, # Price level where spoofing detected
545+
"side": str, # "bid" or "ask"
546+
"order_size": int, # Typical order size at this level
547+
"placement_frequency": float, # Orders placed per minute
548+
"cancellation_rate": float, # Percentage of orders cancelled (0.0-1.0)
549+
"time_to_cancel_avg_seconds": float, # Average time before cancellation
550+
"distance_from_market": int, # Distance in ticks from best bid/ask
551+
"confidence": float, # Confidence score (0.0-1.0)
552+
"pattern": str, # Type of spoofing pattern detected
553+
# "layering", "quote_stuffing", "momentum_ignition",
554+
# "flashing", "wash_trading", "basic_spoofing"
555+
"first_detected": str, # ISO timestamp of first detection
556+
"last_detected": str, # ISO timestamp of most recent detection
557+
"total_instances": int # Number of instances detected
558+
}
559+
]
560+
412561
Performance Considerations
413562
-------------------------
414563

0 commit comments

Comments
 (0)