feat(limitless): implement WebSocket support for real-time market data#27
feat(limitless): implement WebSocket support for real-time market data#27
Conversation
0xghXst
commented
Dec 21, 2025
- Introduced LimitlessWebSocket and LimitlessUserWebSocket classes for handling real-time updates.
- Added methods for subscribing to orderbook and price updates, as well as position tracking for authenticated users.
- Enhanced the Limitless exchange to support WebSocket connections, allowing for real-time orderbook and price data retrieval.
- Updated the strategy cleanup process to include cancellation of orders and liquidation of positions.
- Added tests for WebSocket functionality, ensuring proper callback registration and data parsing.
- Updated documentation to reflect new WebSocket capabilities and usage examples.
- Introduced LimitlessWebSocket and LimitlessUserWebSocket classes for handling real-time updates. - Added methods for subscribing to orderbook and price updates, as well as position tracking for authenticated users. - Enhanced the Limitless exchange to support WebSocket connections, allowing for real-time orderbook and price data retrieval. - Updated the strategy cleanup process to include cancellation of orders and liquidation of positions. - Added tests for WebSocket functionality, ensuring proper callback registration and data parsing. - Updated documentation to reflect new WebSocket capabilities and usage examples.
…Socket and Limitless classes - Consolidated list comprehensions for no bids and no asks in LimitlessWebSocket. - Simplified inverted bids and asks creation in Limitless class for better readability. - Improved code clarity by reducing line count while maintaining functionality.
Code Review: WebSocket Support for Limitless ExchangeSummaryThis PR introduces comprehensive WebSocket support for the Limitless exchange, enabling real-time market data updates. The implementation is well-structured and follows good practices, but there are several areas that need attention. Critical Issues1. Price Normalization Logic Inconsistency (
|
Code Review: WebSocket Support for Limitless ExchangeSummaryThis PR adds comprehensive WebSocket support for the Limitless exchange, including real-time orderbook updates, price data, and position tracking. Overall, this is a well-structured implementation with good test coverage. Below are detailed findings organized by category. Positive Highlights
Issues & Recommendations1. CRITICAL: Race Condition in WebSocket Lifecycle (limitless_ws.py:483-492)Issue: The # Current implementation
def start(self) -> threading.Thread:
self.loop = asyncio.new_event_loop()
async def _run():
await self.connect() # No guarantee connection is ready
while self.state != WebSocketState.CLOSED:
await asyncio.sleep(1)
# ...
self._thread.start()
return self._thread # Returns immediatelyRecommendation: Add a connection ready event: def __init__(self, ...):
# Add to initialization
self._ready = threading.Event()
async def connect(self):
# ... existing code ...
await self.sio.connect(...)
self._ready.set() # Signal ready
def start(self):
# ... existing code ...
self._thread.start()
self._ready.wait(timeout=5) # Wait for connection
return self._thread2. Resource Leak: Event Loop Not Closed (limitless_ws.py:486)Issue: Fix: def _thread_target():
asyncio.set_event_loop(self.loop)
try:
self.loop.run_until_complete(_run())
except Exception as e:
if self.verbose:
logger.error(f"WebSocket thread error: {e}")
finally:
self.loop.close() # Add this3. Bug:
|
… handling - Added a timeout parameter to the start() method to control connection establishment duration. - Introduced a threading.Event to signal when the WebSocket connection is ready. - Updated the stop() method to include a timeout for disconnecting and cleaning up the background thread. - Improved error handling during connection setup and shutdown processes.
Pull Request Review: WebSocket Support for Limitless ExchangeOverviewThis PR adds comprehensive WebSocket support for real-time market data on the Limitless exchange. The implementation is well-structured and includes solid test coverage. Code Quality & Best PracticesStrengths ✅
Areas for Improvement
|
Pull Request Review: Limitless WebSocket ImplementationSummaryThis PR introduces WebSocket support for the Limitless exchange, adding real-time market data capabilities. The implementation is well-structured with good test coverage, but there are several areas that need attention before merging. Critical Issues1. Incomplete Trade Dataclass ImplementationLocation: limitless_ws.py:71-80 The Trade dataclass has several required fields but many default to empty strings (outcome, taker, maker, transaction_hash). This suggests incomplete implementation or these fields should be Optional. Recommendation: Make these fields Optional[str] = None if they are not always available, or ensure they are properly populated. 2. Thread Safety ConcernsLocation: limitless_ws.py:396-402 The callback execution mixes sync/async without proper safety. Synchronous callbacks block the event loop. Recommendation: Use asyncio.to_thread() or loop.run_in_executor() for sync callbacks to avoid blocking. 3. Price Normalization InconsistencyLocation: limitless.py:374-393 Price normalization logic is duplicated and complex. The heuristic (divide by 100 if > 1) could fail edge cases. Recommendation: Add explicit price format metadata from API or use a more robust detection method. 4. Missing Error Handling in CleanupLocation: strategy.py:578-588 The cleanup process has a bare except Exception: pass which silently fails. Recommendation: At minimum log the error for debugging; consider re-raising critical errors. Security Concerns5. Session Cookie HandlingLocation: limitless.py:1582-1586 Cookies are extracted manually. Consider secure cookie handling best practices. Recommendation: Ensure cookies are handled securely; avoid logging them. 6. No Input Validation on WebSocket MessagesLocation: limitless_ws.py:236-280 The parsing functions use float() and int() without validation. Malformed WebSocket messages could cause crashes. Recommendation: Add try/except with proper error handling around type conversions. Code Quality Issues7. Orderbook Inversion Logic ComplexityLocation: limitless.py:500-517 The No token orderbook inversion is clever but complex, hard to test and verify correctness. Rounding to 3 decimals may cause precision issues. Recommendation: Extract to a separate well-tested method with comprehensive tests. 8. Magic NumbersLocation: limitless.py:301 Hard-coded value: limit = min(query_params.get("limit", 25), 25) Recommendation: Define MAX_MARKETS_PER_PAGE = 25 as a class constant. 9. Hardcoded Sleep in CleanupLocation: strategy.py:577 time.sleep(3) - Arbitrary 3-second wait may be too short or too long Recommendation: Make configurable or poll for order completion. 10. Duplicate Token Mapping LogicToken-to-slug mapping exists in both WebSocket and Exchange classes. Potential for inconsistency. Recommendation: Consider centralizing this mapping logic. Performance Considerations11. Synchronous Request in Orderbook FetchLocation: limitless.py:449-517 The get_orderbook method makes synchronous HTTP requests. Could benefit from async implementation. Recommendation: Consider adding an async variant for better performance. 12. No Connection Pooling ConfigurationWebSocket reconnection settings use infinite reconnection which could cause issues. Recommendation: Add configurable max reconnection attempts with exponential backoff. Test CoverageStrengths:
Gaps:
Recommendation: Add integration tests (can use mock WebSocket server) and test orderbook inversion thoroughly. Best Practices & Style (per CLAUDE.md)Following Guidelines:
DocumentationGood Documentation:
Could Improve:
Recommendations SummaryMust Fix Before Merge:
Should Fix:
Nice to Have:
Overall AssessmentQuality: Good This is a solid implementation with good structure and testing. The main concerns are around thread safety, error handling, and edge case validation. Once the critical issues are addressed, this will be ready to merge. Great work on the WebSocket implementation overall! |
…cellation - Enhanced the stop() method in ExchangeClient to ensure all pending tasks are canceled before stopping the event loop. - Added logic to handle the cancellation of tasks in the market WebSocket loop, improving resource management during shutdown. - Updated Limitless class to refine size determination from API responses, ensuring accurate order size calculations based on market conditions.
Pull Request Review: WebSocket Support for Limitless ExchangeOverall AssessmentThis is a solid implementation that adds real-time market data capabilities through WebSocket connections. The code is well-structured, includes comprehensive tests, and follows good practices. However, there are several areas that need attention before merging. Critical Issues1. Race Condition in Event Loop Shutdown (exchange_client.py:488)
2. Hard-Coded Sleep in Cleanup (strategy.py:577)
3. Missing Error Handling in WebSocket Callbacks (limitless_ws.py:164-179)
Security Concerns4. Session Cookie Handling (limitless.py:1601)
5. Credential Logging
Code Quality Issues6. Duplicate Code in Orderbook Inversion
7. Inconsistent Rounding Precision (limitless.py:508)
8. Silent Exception Handling (strategy.py:588)
Performance Considerations9. Inefficient List Operations (limitless_ws.py:415-416)
10. Busy-Wait Loop (limitless_ws.py:405-406)
Best Practices11. Price Normalization Logic (limitless.py:376-387)
12. Magic Numbers (limitless.py:958-960)
Test CoveragePositive: Comprehensive unit tests, good error case coverage Recommendations SummaryMust Fix Before Merge:
Should Fix: Nice to Have: ConclusionThis PR adds valuable real-time capabilities. Implementation is well-designed but critical threading issues and cleanup logic need addressing before merge. Recommendation: Request changes for critical issues, then approve after fixes. |