-
Notifications
You must be signed in to change notification settings - Fork 15
Enhance ExchangeClient and introduce Spike Strategy #44
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
- Improved WebSocket shutdown process in ExchangeClient to ensure proper disconnection and task cancellation. - Added a new SpikeStrategy class for mean reversion trading, which detects price spikes and executes buy orders based on defined thresholds and conditions. - Included detailed logging for strategy configuration and execution, enhancing observability during trading operations.
Code Review: PR #44 - Enhance ExchangeClient and introduce Spike StrategySummaryThis PR improves the WebSocket shutdown process and adds a new mean reversion trading strategy. Overall the changes are well-implemented, but there are several areas for improvement. Code Quality & Best PracticesPositives:
Issues:
Potential Bugs & Issues
Performance Considerations
Security Concerns
Test CoverageCritical Issue: No tests were added for either change.
Consider adding at minimum:
RecommendationsHigh Priority:
Medium Priority: Low Priority: Positive Notes
Overall, this is a solid contribution that adds useful functionality, but needs refinement to meet the project's quality and testing standards. |
- Handle race condition in WebSocket shutdown with try-except - Add debug logging for disconnect exceptions - Add division by zero protection for entry_price - Validate ask price <= 1.0 for Polymarket 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
PR Review: Spike Strategy and ExchangeClient ImprovementsSummaryThis PR introduces a new mean reversion trading strategy and improves WebSocket shutdown handling. Overall, the code is well-structured and follows the repository patterns, but there are several areas that need attention. Code Quality & Best PracticesPositive Aspects
Issues Found1. Code Duplication - DRY Principle Violation The find_market_id() function in spike_strategy.py (lines 268-304) is nearly identical to the one in spread_strategy.py (lines 37-87). This is 37 lines of duplicated code. Recommendation: Extract to a shared utility module (dr_manhattan/utils/market_lookup.py) and import in both strategies. Potential Bugs & IssuesCritical Issues1. Race Condition in Position Management In _manage_position() at spike_strategy.py:187-192, there is a bug where positions < 1 share are deleted. Position could be 0.5 shares which is valid, but would be deleted. Should check <= 0 instead of < 1. 2. Incomplete Cleanup Logic In cleanup() at spike_strategy.py:236-259, the code silently catches ALL exceptions with bare except and no logging when cleanup fails. Add proper error logging. 3. Validation Gap for Polymarket Line 162 validates ask > 1.0, which is Polymarket-specific (prices are probabilities 0-1). This makes the strategy not exchange-agnostic. Consider documenting this limitation. Performance Considerations1. Inefficient Price History Storage Stores 60 price samples per outcome but EMA period default is 30. Either reduce maxlen to match ema_period or use the history for additional analytics. 2. Multiple get_best_bid_ask Calls In _check_spike_and_buy(), the code calls get_best_bid_ask() twice for the same token. Cache the result. Security Concerns1. No Maximum Position Validation The strategy checks cash but doesn't validate that max_position is sensible relative to account size. A user could set max_position=1000000 with only 00. 2. Price Manipulation Risk Spike detection could be triggered by flash crashes, orderbook manipulation, or WebSocket glitches. Add minimum volume/liquidity checks and maximum spike size validation. 3. No Order Size Validation Missing validation for minimum order size, maximum order size relative to liquidity, and dust position handling. Test CoverageCritical: Missing Tests No tests were added for the new SpikeStrategy class. The PR adds 389 lines with 0% test coverage. Required tests:
Recommendation: Add tests/test_spike_strategy.py following the pattern in tests/test_base.py ExchangeClient ChangesWebSocket Shutdown Improvements ✅The changes in exchange_client.py are solid with proper timeout handling (3s), specific exception catching, graceful degradation with debug logging, and proper disconnect before stopping loop. Minor suggestion: Consider making timeout configurable or documenting why 3s was chosen. SummaryBlocking Issues
Recommended Before Merge
The strategy implementation is promising, but needs test coverage and bug fixes before merging. |
- Introduced documentation for the new spike_strategy.py, detailing its mean reversion functionality and usage instructions. - Updated SpikeStrategy class to include token_id in price retrieval and position management methods, improving accuracy and handling of market data. - Added error logging for cleanup failures during position management. This commit enhances both the usability and robustness of the spike trading strategy.
Pull Request Review: Spike Strategy ImplementationSummaryThis PR introduces a mean reversion trading strategy and improves WebSocket shutdown handling. The changes include:
Code Quality & Best PracticesStrengths
Issues & Recommendations1. WebSocket Shutdown Logic (exchange_client.py:482-492)The new disconnect approach is better than the old task cancellation, but there are concerns: future = asyncio.run_coroutine_threadsafe(
self._market_ws.disconnect(), self._market_ws.loop
)
future.result(timeout=3.0)Issue: If Recommendation: Consider adding a disconnect flag check or using if not self._market_ws._disconnected: # if you have such a flag
future = asyncio.run_coroutine_threadsafe(...)2. Price Validation Missing (spike_strategy.py:163-164)if ask is None or ask <= 0 or ask > 1.0:
returnGood: You validate the ask price is between 0-1 for binary markets. Issue: The mid-price calculation in Recommendation: if bid is None or ask is None or bid <= 0 or ask <= 0 or bid >= ask:
return self.market.prices.get(outcome)3. Potential Division by Zero (spike_strategy.py:190-196)if pos.entry_price <= 0:
del self.entries[outcome]
return
pnl = (price - pos.entry_price) / pos.entry_priceGood: You check for Issue: However, if Recommendation: Add price validation before PnL calculation: if price is None or price <= 0 or pos.entry_price <= 0:
del self.entries[outcome]
return4. EMA Initialization (spike_strategy.py:135-140)The EMA initialization uses the first price it sees: if self.ema_prices[outcome] == 0.0:
self.ema_prices[outcome] = priceIssue: This means the strategy behavior depends on what price happens to come first, and the EMA won't be meaningful until if ema <= 0 or len(self.price_history[outcome]) < self.ema_period:
return FalseGood: You wait for enough history before trading. This is correct. 5. Position Size Mismatch Risk (spike_strategy.py:207-210)exit_size = min(exchange_pos, pos.size)Issue: Recommendation: Just use exit_size = exchange_pos6. Code Duplication (spike_strategy.py:266-292 vs spread_strategy.py:37-87)The Recommendation: Extract this to a shared utility module: # dr_manhattan/utils/market.py
def find_market_id(exchange: Exchange, slug: str, market_index: Optional[int] = None) -> Optional[str]:
...Then import it in both strategy files. Performance Considerations
Minor Optimization: The Security ConcernsHigh Priority
Medium Priority
Test CoverageCritical Issue: There are NO tests for the new SpikeStrategy class. The PR adds 390 lines of new code with complex logic (EMA calculation, spike detection, position management, PnL tracking) but zero test coverage. Recommendations:
Example test structure: # tests/test_spike_strategy.py
def test_ema_calculation():
strategy = SpikeStrategy(...)
# Test EMA converges to correct value
def test_spike_detection_below_threshold():
# Test it DOES trigger when price drops > threshold
def test_no_spike_detection_above_threshold():
# Test it DOES NOT trigger when price drop < threshold
def test_position_exit_on_profit_target():
# Test position exits when profit target hitAdherence to CLAUDE.md✅ Good
|
- Updated README.md to include a new section for trading strategies, linking to the Spread and Spike strategies. - Added detailed documentation for the Spike Strategy, outlining its mean reversion approach and usage instructions. - Introduced documentation for the Spread Strategy, describing its market-making functionality and parameters.
PR Review: Enhance ExchangeClient and introduce Spike StrategyOverviewThis PR introduces a mean reversion trading strategy (SpikeStrategy) and improves WebSocket shutdown handling. Overall well-structured implementation with good documentation. Code Quality & Best PracticesStrengths:
Areas for Improvement:
Potential Bugs & IssuesCritical:
Moderate:
Test CoverageMissing:
Recommendations:
Documentation QualityStrengths:
Additional ObservationsPositive:
Suggestions:
RecommendationApprove with minor changes requested The PR introduces valuable functionality with good documentation. The critical issues around position tracking and stale prices should be addressed. Priority fixes:
|
🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Pull Request Review: Enhance ExchangeClient and introduce Spike StrategyOverviewThis PR introduces a new mean reversion trading strategy (SpikeStrategy) and improves the WebSocket shutdown process. The changes are well-structured and add valuable functionality to the codebase. Code Quality & Best Practices✅ Strengths
|
close #34