-
Notifications
You must be signed in to change notification settings - Fork 15
Restructure: introduce exchange_client, strategy class #23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
guzus
commented
Dec 19, 2025
- refactor: restructure exchange architecture with client and strategy abstractions
- refactor(strategy): introduce OutcomeToken model and simplify outcome/token management
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
…/token management
…cing - Add Orderbook model for structured orderbook data representation - Implement setup_orderbook_websocket() to establish real-time orderbook updates via WebSocket - Add get_best_bid_ask() method with fallback to REST API when WebSocket unavailable - Add update_mid_price_from_orderbook() to cache mid-prices from orderbook data - Add fetch_positions_dict_for_market() helper for market-specific position queries - Update calculate_nav() to use market-specific positions when market provided - Add market WebSocket connection management with background thread handling - Import asyncio and threading for async WebSocket operations - Add orderbook manager initialization and lifecycle management in ExchangeClient - Update stop() method to properly close market WebSocket connections - Enables real-time pricing data for more accurate strategy execution
…organization - Add Callable type import for callback type hints - Restructure positions cache from flat list to per-market dictionary with timestamps for better granularity and TTL management - Improve WebSocket error handling with specific exception types (ConnectionError vs generic Exception) and proper logging - Add performance monitoring for initial orderbook fetch with duration logging when exceeding 1 second threshold - Implement proper async task lifecycle management in WebSocket event loop with try-catch-finally cleanup - Extract price level parsing logic into dedicated _parse_price_level() method to reduce code duplication in get_best_bid_ask() - Replace verbose print statements with structured logger calls for better observability - Update get_positions() to use per-market cache keys and check freshness before updating - Add explanatory comments for N+1 query pattern and potential optimization opportunities - Improve exception handling in background update tasks with consistent logging approach
- Change side field from 0/1 to 1/2 to match Opinion API convention (1=Buy, 2=Sell) - Add side_enum mock to prevent MagicMock auto-creation in tests - Rename maker_amount to order_shares to reflect Opinion API naming - Rename matched_amount to filled_shares to reflect Opinion API naming - Rename position size field to shares_owned for Opinion API compatibility - Rename average_price to avg_entry_price to match Opinion API field names - Update balance response structure to use available_balance and balances array - Add clarifying comments documenting Opinion API field mappings - Ensures test mocks accurately represent actual Opinion API response structure
Code Review - PR #23: Restructure with ExchangeClient and StrategySummaryThis PR introduces a significant architectural refactoring that separates concerns between stateless exchange operations and stateful client management. Overall, the design is solid and follows good separation of concerns principles. However, there are several areas that need attention before merging. Architecture Changes ✅Positives:
Concerns:
Code Quality Issues1. Missing Test Coverage
|
Pull Request Review: Restructure Exchange ArchitectureSummaryThis PR introduces a significant architectural improvement by separating stateless exchange operations from stateful client management, and providing a base Strategy class for building trading bots. Overall, this is a well-designed refactoring that improves code organization and reusability. ✅ Strengths1. Excellent Separation of Concerns
2. Improved Code Reusability
3. Enhanced Developer Experience
4. Good Testing
🔍 Code Quality Issues1. Performance: N+1 Query Pattern
|
| Guideline | Status | Notes |
|---|---|---|
| 1. Focused, clean, easy to understand | ✅ | Code is well-organized |
| 2. Don't create new documents | ✅ | No new docs added |
| 3. Only use UV | Can't verify without CI/CD info | |
| 4. Single Source of Truth | ❌ | Heavy use of env vars in examples |
| 5. Run and Debug proactively | ❌ | No evidence tests were run |
Recommendation:
- Address guideline fix: polymarket impl #4 (env vars vs code)
- Add CI/CD workflow to verify tests pass
🎯 Overall Assessment
Code Quality: B+ (Good with some issues to address)
Architecture: A (Excellent separation of concerns)
Testing: C+ (Adequate but gaps exist)
Security: A- (Good validation, minor improvements possible)
🚀 Recommendations Priority
High Priority (Fix before merge):
- ✅ Fix daemon thread shutdown issue
- ✅ Fix WebSocket exception handling (cleanup state)
- ✅ Resolve CLAUDE.md compliance issue with env vars
Medium Priority (Fix soon):
- Add tests for ExchangeClient and Strategy
- Document N+1 query pattern limitation
- Fix cache invalidation edge case
- Add docstrings to Strategy helper methods
Low Priority (Future improvement):
- Standardize type annotations
- Consider batch orderbook fetching
- Add integration tests
✅ Approval Recommendation
This PR should be APPROVED with requested changes.
The architectural improvements are valuable and the code is generally well-written. The issues identified are manageable and don't block the core functionality. Address the high-priority items before merging, and create follow-up issues for medium/low priority items.
Great work on this refactoring! The new architecture will make it much easier to build and maintain trading strategies. 🎉
Pull Request Review: Restructure Exchange ArchitectureThis is a major refactoring that introduces significant architectural improvements. Overall, this is excellent work that substantially improves the codebase quality and maintainability. Below is a detailed review. ✅ Strengths1. Excellent Separation of ConcernsThe introduction of
This follows the Single Responsibility Principle and makes the codebase much more maintainable. 2. Factory Pattern ImplementationThe
3. Code ConsolidationRemoving duplicate spread strategies (588 + 605 lines) and consolidating into a single 136-line implementation is a significant improvement that aligns with CLAUDE.md directive #2 ("Purge unnecessary code"). 4. WebSocket Orderbook SupportThe orderbook WebSocket implementation in
5. Improved Caching StrategyPer-market position caching with TTL is much better than the previous flat cache: # Before: _positions_cache = []
# After: _positions_cache: Dict[str, Tuple[List[Position], float]] = {}6. Test UpdatesThe test updates to match Opinion API field names (
|
…book polling fallback
…handling - Extract tick size rounding logic into dedicated utils/price.py module - Remove get_tick_size, round_to_tick_size, and is_valid_price methods from Exchange base class - Remove tick size delegation methods from ExchangeClient - Update Strategy to use Market.tick_size directly and import round_to_tick_size from utils - Add tick_size field to Market model for centralized price precision configuration - Update Limitless exchange to set tick_size to 0.001 and pass to Market constructor - Update Opinion exchange to set tick_size to 0.001 and pass to Market constructor - Remove get_websocket stub method from Exchange base class - Add exchange documentation for Limitless and Opinion platforms - Consolidate price handling logic into reusable utility functions for better maintainability
PR Review: Restructure exchange architecture with client and strategy abstractionsSummaryThis is a significant architectural refactor that introduces better separation of concerns by splitting exchange functionality into stateless Overall Assessment: ✅ Approve with minor recommendations Positive ChangesArchitecture Improvements
Code Quality
Issues & Recommendations1. CRITICAL: Incomplete diff in exchange_client.py (dr_manhattan/base/exchange_client.py:318)The diff shows truncated code at line 318 in def _setup_orderbook_polling(self, token_ids: List[str], interval: float = 0.5) -> bool:
...
# Initial fetAction Required: The method appears incomplete. Please verify this is not a git diff artifact and that the full implementation is present. 2. Missing Test CoverageSeverity: High Major new components lack tests:
Recommendation: Add comprehensive unit tests for:
3. Type Safety IssuesSeverity: Medium (dr_manhattan/base/exchange_config.py:47) ExchangeConfig = PolymarketConfig | OpinionConfig | LimitlessConfigThis union type alias works but could be more explicit. Consider using Recommendation: from typing import Union
ExchangeConfig = Union[PolymarketConfig, OpinionConfig, LimitlessConfig]4. Security: Private Key Validation (dr_manhattan/base/exchange_factory.py:144-177)Severity: Medium Good: Private key validation exists
Recommendations:
5. Resource ManagementSeverity: Medium (dr_manhattan/base/exchange_client.py:293-370) WebSocket and thread management in self._ws_thread = None
self._polling_thread = NoneConcerns:
Recommendation:
6. Error Handling in Caching (dr_manhattan/base/exchange_client.py:449-500)Severity: Low Cache update failures are caught but may leave stale data: except Exception as e:
logger.warning(f"Failed to update balance cache: {e}")Recommendation: Consider adding cache invalidation on error or returning stale data with a warning flag. 7. Performance: Polling FallbackSeverity: Low (dr_manhattan/base/exchange_client.py:318-370) REST polling as WebSocket fallback could be expensive:
Recommendation:
Code Quality DetailsStyle Adherence to CLAUDE.md ✅
Best Practices
Security Checklist
Performance ConsiderationsPositive
Concerns
Migration PathThe PR removes old exchange-specific strategy files:
Question: Are there any users of these files who need a migration guide? Consider adding a MIGRATION.md if this is a public library. Recommendations SummaryMust Fix
Should Fix
Nice to Have
ConclusionThis is a well-designed refactor that significantly improves the codebase architecture. The separation of stateful/stateless concerns and the Strategy pattern are excellent decisions. Main blocker: Lack of test coverage for ~2000+ lines of new core functionality. Once tests are added and the truncation issue is verified, this PR will be in excellent shape. The architectural foundation is solid and sets the codebase up for easier extension to new exchanges. Great work on the refactor! 🚀 |
- Add tick_size=0.01 to all Market instantiations in test_base.py MockExchange - Add tick_size=0.01 to Market fixtures in test_limitless.py helper method tests - Add tick_size=0.01 to all Market test cases in test_models.py - Add minimum_tick_size field to mock Polymarket API response in test_polymarket.py - Ensure test fixtures match updated Market model schema with tick_size field
Pull Request Review: Restructure Exchange ArchitectureOverviewThis PR introduces a significant architectural refactoring that separates concerns between stateless exchange operations and stateful client management. The changes include:
Architecture & Design ✅ EXCELLENTStrengths:
Code Quality & Best Practices ✅ GOODStrengths:
Concerns: 🔴 CRITICAL: Violates CLAUDE.md Principle #4The -.env.example (BEFORE - Good, follows CLAUDE.md #4):
+# Your proxy wallet's private key (without 0x prefix)
+POLYMARKET_PRIVATE_KEY=your_private_key_here
+.env.example (AFTER - Bad, violates CLAUDE.md #4):
+POLYMARKET_PRIVATE_KEY=0x1234567890abcdef...Issue: Real example values in Recommendation: Revert
|