@@ -338,7 +338,34 @@ def _trigger_callbacks(self, event_type: str, data: Any):
338338 self .logger .error (f"Error in { event_type } callback: { e } " )
339339
340340 def add_callback (self , event_type : str , callback ):
341- """Add a callback for order events."""
341+ """
342+ Register a callback function for specific order events.
343+
344+ Allows you to listen for order fills, cancellations, rejections, and other
345+ order status changes to build custom monitoring and notification systems.
346+
347+ Args:
348+ event_type: Type of event to listen for
349+ - "order_filled": Order completely filled
350+ - "order_cancelled": Order cancelled
351+ - "order_expired": Order expired
352+ - "order_rejected": Order rejected by exchange
353+ - "order_pending": Order pending submission
354+ - "trade_execution": Trade execution notification
355+ callback: Function to call when event occurs
356+ Should accept one argument: the order data dict
357+
358+ Example:
359+ >>> def on_order_filled(order_data):
360+ ... print(
361+ ... f"Order filled: {order_data.get('id')} - {order_data.get('contractId')}"
362+ ... )
363+ ... print(f"Fill volume: {order_data.get('fillVolume', 0)}")
364+ >>> order_manager.add_callback("order_filled", on_order_filled)
365+ >>> def on_order_cancelled(order_data):
366+ ... print(f"Order cancelled: {order_data.get('id')}")
367+ >>> order_manager.add_callback("order_cancelled", on_order_cancelled)
368+ """
342369 self .order_callbacks [event_type ].append (callback )
343370
344371 # ================================================================================
@@ -347,13 +374,29 @@ def add_callback(self, event_type: str, callback):
347374
348375 def get_tracked_order_status (self , order_id : str ) -> dict [str , Any ] | None :
349376 """
350- Get cached order status from realtime tracking.
377+ Get cached order status from real-time tracking for faster access.
378+
379+ When real-time mode is enabled, this method provides instant access to
380+ order status without requiring API calls, improving performance.
351381
352382 Args:
353- order_id: Order ID to get status for
383+ order_id: Order ID to get status for (as string)
354384
355385 Returns:
356- dict: Order data if tracked, None otherwise
386+ dict: Complete order data if tracked in cache, None if not found
387+ Contains all ProjectX GatewayUserOrder fields:
388+ - id, accountId, contractId, status, type, side, size
389+ - limitPrice, stopPrice, fillVolume, filledPrice, etc.
390+
391+ Example:
392+ >>> order_data = order_manager.get_tracked_order_status("12345")
393+ >>> if order_data:
394+ ... print(
395+ ... f"Status: {order_data['status']}"
396+ ... ) # 1=Open, 2=Filled, 3=Cancelled
397+ ... print(f"Fill volume: {order_data.get('fillVolume', 0)}")
398+ >>> else:
399+ ... print("Order not found in cache")
357400 """
358401 with self .order_lock :
359402 return self .tracked_orders .get (order_id )
@@ -362,11 +405,22 @@ def is_order_filled(self, order_id: str | int) -> bool:
362405 """
363406 Check if an order has been filled using cached data with API fallback.
364407
408+ Efficiently checks order fill status by first consulting the real-time
409+ cache (if available) before falling back to API queries for maximum
410+ performance.
411+
365412 Args:
366- order_id: Order ID to check (str or int )
413+ order_id: Order ID to check (accepts both string and integer )
367414
368415 Returns:
369- bool: True if order is filled
416+ bool: True if order status is 2 (Filled), False otherwise
417+
418+ Example:
419+ >>> if order_manager.is_order_filled(12345):
420+ ... print("Order has been filled")
421+ ... # Proceed with next trading logic
422+ >>> else:
423+ ... print("Order still pending")
370424 """
371425 order_id_str = str (order_id )
372426
@@ -382,7 +436,15 @@ def is_order_filled(self, order_id: str | int) -> bool:
382436 return order is not None and order .status == 2 # 2 = Filled
383437
384438 def clear_order_tracking (self ):
385- """Clear internal order tracking cache."""
439+ """
440+ Clear internal order tracking cache for memory management.
441+
442+ Removes all cached order data from the real-time tracking system.
443+ Useful for memory cleanup or when restarting order monitoring.
444+
445+ Example:
446+ >>> order_manager.clear_order_tracking()
447+ """
386448 with self .order_lock :
387449 self .tracked_orders .clear ()
388450 self .order_status_cache .clear ()
@@ -1374,12 +1436,25 @@ def track_order_for_position(
13741436 self , order_id : int , contract_id : str , order_category : str
13751437 ):
13761438 """
1377- Track an order as being related to a position.
1439+ Track an order as being related to a position for synchronization.
1440+
1441+ Establishes a relationship between an order and a position to enable
1442+ automatic order management when positions change (size adjustments,
1443+ closures, etc.).
13781444
13791445 Args:
13801446 order_id: Order ID to track
13811447 contract_id: Contract ID the order relates to
1382- order_category: Category: 'entry', 'stop', or 'target'
1448+ order_category: Order category for the relationship:
1449+ - 'entry': Entry orders that create positions
1450+ - 'stop': Stop loss orders for risk management
1451+ - 'target': Take profit orders for profit taking
1452+
1453+ Example:
1454+ >>> # Track a stop loss order for MGC position
1455+ >>> order_manager.track_order_for_position(12345, "MGC", "stop")
1456+ >>> # Track a take profit order
1457+ >>> order_manager.track_order_for_position(12346, "MGC", "target")
13831458 """
13841459 with self .order_lock :
13851460 if order_category in ["entry" , "stop" , "target" ]:
@@ -1392,10 +1467,16 @@ def track_order_for_position(
13921467
13931468 def untrack_order (self , order_id : int ):
13941469 """
1395- Remove order from position tracking.
1470+ Remove order from position tracking when no longer needed.
1471+
1472+ Removes the order-position relationship, typically called when orders
1473+ are filled, cancelled, or expired.
13961474
13971475 Args:
1398- order_id: Order ID to untrack
1476+ order_id: Order ID to remove from tracking
1477+
1478+ Example:
1479+ >>> order_manager.untrack_order(12345)
13991480 """
14001481 with self .order_lock :
14011482 contract_id = self .order_to_position .pop (order_id , None )
@@ -1410,13 +1491,26 @@ def untrack_order(self, order_id: int):
14101491
14111492 def get_position_orders (self , contract_id : str ) -> dict [str , list [int ]]:
14121493 """
1413- Get all orders related to a position.
1494+ Get all orders related to a specific position.
1495+
1496+ Retrieves all tracked orders associated with a position, organized
1497+ by category for position management and synchronization.
14141498
14151499 Args:
14161500 contract_id: Contract ID to get orders for
14171501
14181502 Returns:
1419- Dict with lists of order IDs by category
1503+ Dict with lists of order IDs organized by category:
1504+ - entry_orders: List of entry order IDs
1505+ - stop_orders: List of stop loss order IDs
1506+ - target_orders: List of take profit order IDs
1507+
1508+ Example:
1509+ >>> orders = order_manager.get_position_orders("MGC")
1510+ >>> print(f"Stop orders: {orders['stop_orders']}")
1511+ >>> print(f"Target orders: {orders['target_orders']}")
1512+ >>> if orders["entry_orders"]:
1513+ ... print(f"Entry orders still pending: {orders['entry_orders']}")
14201514 """
14211515 with self .order_lock :
14221516 return {
@@ -1691,10 +1785,31 @@ def _align_price_to_tick_size(
16911785
16921786 def get_order_statistics (self ) -> dict [str , Any ]:
16931787 """
1694- Get order management statistics.
1788+ Get comprehensive order management statistics and system health information.
1789+
1790+ Provides detailed metrics about order activity, real-time tracking status,
1791+ position-order relationships, and system health for monitoring and debugging.
16951792
16961793 Returns:
1697- Dict with statistics and health information
1794+ Dict with complete statistics including:
1795+ - statistics: Core order metrics (placed, cancelled, modified, etc.)
1796+ - realtime_enabled: Whether real-time order tracking is active
1797+ - tracked_orders: Number of orders currently in cache
1798+ - position_order_relationships: Details about order-position links
1799+ - callbacks_registered: Number of callbacks per event type
1800+ - health_status: Overall system health status
1801+
1802+ Example:
1803+ >>> stats = order_manager.get_order_statistics()
1804+ >>> print(f"Orders placed: {stats['statistics']['orders_placed']}")
1805+ >>> print(f"Real-time enabled: {stats['realtime_enabled']}")
1806+ >>> print(f"Tracked orders: {stats['tracked_orders']}")
1807+ >>> relationships = stats["position_order_relationships"]
1808+ >>> print(
1809+ ... f"Positions with orders: {relationships['positions_with_orders']}"
1810+ ... )
1811+ >>> for contract_id, orders in relationships["position_summary"].items():
1812+ ... print(f" {contract_id}: {orders['total']} orders")
16981813 """
16991814 with self .order_lock :
17001815 # Use internal order tracking
@@ -1738,10 +1853,31 @@ def get_order_statistics(self) -> dict[str, Any]:
17381853
17391854 def get_realtime_validation_status (self ) -> dict [str , Any ]:
17401855 """
1741- Get validation status for real-time order feed integration.
1856+ Get validation status for real-time order feed integration and compliance.
1857+
1858+ Provides detailed information about real-time integration status,
1859+ payload validation settings, and ProjectX API compliance for debugging
1860+ and system validation.
17421861
17431862 Returns:
1744- Dict with validation metrics and status information
1863+ Dict with comprehensive validation status including:
1864+ - realtime_enabled: Whether real-time updates are active
1865+ - tracked_orders_count: Number of orders being tracked
1866+ - order_callbacks_registered: Number of order update callbacks
1867+ - payload_validation: Settings for validating ProjectX order payloads
1868+ - projectx_compliance: Compliance status with ProjectX API format
1869+ - statistics: Current order management statistics
1870+
1871+ Example:
1872+ >>> status = order_manager.get_realtime_validation_status()
1873+ >>> print(f"Real-time enabled: {status['realtime_enabled']}")
1874+ >>> print(f"Tracking {status['tracked_orders_count']} orders")
1875+ >>> compliance = status["projectx_compliance"]
1876+ >>> for check, result in compliance.items():
1877+ ... print(f"{check}: {result}")
1878+ >>> # Validate order status enum understanding
1879+ >>> status_enum = status["payload_validation"]["order_status_enum"]
1880+ >>> print(f"Filled status code: {status_enum['Filled']}")
17451881 """
17461882 # Use internal order tracking
17471883 with self .order_lock :
@@ -1797,7 +1933,17 @@ def get_realtime_validation_status(self) -> dict[str, Any]:
17971933 }
17981934
17991935 def cleanup (self ):
1800- """Clean up resources and connections."""
1936+ """
1937+ Clean up resources and connections when shutting down.
1938+
1939+ Properly shuts down order tracking, clears cached data, and releases
1940+ resources to prevent memory leaks when the OrderManager is no
1941+ longer needed.
1942+
1943+ Example:
1944+ >>> # Proper shutdown
1945+ >>> order_manager.cleanup()
1946+ """
18011947 with self .order_lock :
18021948 self .order_callbacks .clear ()
18031949 self .position_orders .clear ()
0 commit comments