-
-
Notifications
You must be signed in to change notification settings - Fork 11
v3.5.6: Critical Event System and Bracket Order Fixes #68
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
## Problem Events were not firing in multi-instrument scenarios because: - Each InstrumentContext had isolated EventBus with no forwarding to suite - InstrumentContext lacked event methods (wait_for, on, off) - Suite-level handlers never received instrument events ## Solution 1. Added event forwarding from instrument EventBuses to suite EventBus - New EventBus.forward_to() method for event propagation - Automatic forwarding setup in TradingSuite._setup_event_forwarding() 2. Enhanced InstrumentContext with event methods - Added event_bus attribute to dataclass - Implemented on(), once(), off(), wait_for() methods - Methods delegate to instrument's EventBus 3. Updated example to use instrument context event methods - examples/realtime_data/01_basic_realtime_data_streaming.py ## Testing - Added comprehensive tests for event forwarding functionality - tests/test_event_forwarding.py validates core functionality - tests/test_event_system_multi_instrument.py defines expected behavior ## Impact - Suite-level handlers now receive events from all instruments - Instrument-level handlers can filter for specific instruments - Maintains backward compatibility with single-instrument usage - Enables proper event-driven programming with multiple instruments 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Handle nested event data structure (event.data contains timeframe and nested data field) - Add defensive checks for bar data fields - Add debug output when fields are missing - Fix whitespace formatting issues
- Added 16 tests to prevent regression of event system - Tests validate event forwarding from instruments to suite - Tests verify InstrumentContext event methods work correctly - Tests ensure different event types are forwarded properly - Tests confirm event handler lifecycle (on, once, off) - Tests validate event data structure for NEW_BAR events These tests will catch any future breakage of the multi-instrument event system
- Replace validate_price_tick_size with align_price_to_tick_size in bracket orders - Auto-correct misaligned prices to nearest valid tick size - Log when prices are adjusted for transparency - Update core.py to use alignment for all order types - Improves user experience by fixing prices rather than rejecting orders
- Fix async/sync method calls for account info retrieval - Use proper event handlers with Event type hints - Simplify P&L calculation as placeholder - Add automatic price alignment with new bracket order feature - Use TradingSuite features correctly - Clean up unused variables and improve code structure
- Properly handle Polars DataFrames with pipe methods for indicators - Use Event type hints and correct event handling - Fix data access using proper DataFrame methods (tail, columns) - Add automatic price alignment via bracket orders - Improve error handling and add fallback values - Add ATR-based dynamic stop/target calculation - Clean up imports and remove unused polars import - Add comprehensive status updates and trade confirmation
- Fix ATR-based dynamic stop calculations with proper DataFrame operations - Correct Polars DataFrame handling with pipe() method chaining - Update event handlers with proper Event type hints - Fix indicator calculations (RSI, SMA, MACD, EMA) - Use tail() method for accessing last DataFrame rows - Integrate automatic price alignment for bracket orders - Ensure proper async/await usage throughout - Add comprehensive trade setup displays - Fix event-driven trade execution patterns All three advanced examples now demonstrate professional trading patterns using the SDK's async architecture, event system, and bracket orders with automatic tick size alignment. 🤖 Generated with Claude Code Co-Authored-By: Claude <[email protected]>
- Implement Level 2 order book imbalance detection - Add tape reading for momentum confirmation - Include iceberg order detection capabilities - Add volume profile analysis for key levels - Use proper InstrumentContext orderbook access - Implement bracket orders with automatic tick alignment - Add comprehensive market microstructure analysis - Include tight risk management for scalping (3 tick stop, 2 tick target) - Add Event type hints to all handlers - Support max 2 concurrent scalp positions Example demonstrates professional scalping techniques using order book analytics, tape reading, and confluence signals. 🤖 Generated with Claude Code Co-Authored-By: Claude <[email protected]>
- Use get_market_imbalance() instead of non-existent get_imbalance() - Access TypedDict fields with bracket notation where needed - Fix iceberg detection parameters - Correct volume profile method parameters - Remove references to non-existent enable_analytics() - Use get_orderbook_snapshot() as fallback for imbalance calculation - Fix all f-string formatting issues The example now properly uses the OrderBook class methods that actually exist in the SDK. 🤖 Generated with Claude Code Co-Authored-By: Claude <[email protected]>
- Access TypedDict fields using bracket notation - Fix detect_iceberg_orders with correct parameters (min_refreshes, volume_threshold, time_window_minutes) - Fix get_volume_profile with correct parameters (time_window_minutes, price_bins) - Handle None values properly with 'or' operator instead of get() default - Remove unnecessary pass statement - Add proper newline at end of file The example now correctly uses all OrderBook API methods with proper TypedDict field access and correct parameter names. 🤖 Generated with Claude Code Co-Authored-By: Claude <[email protected]>
- Changed from trying to format Polars Series to direct dict access - Access bar data fields directly from event.data['data'] dictionary - Fixes 'unsupported format string passed to Series.__format__' error - Properly displays OHLC, volume, and timestamp for new bars 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
## Multi-Instrument Event System Fixes - Implemented event forwarding from instrument EventBuses to suite EventBus - Added event methods (on, once, off, wait_for) to InstrumentContext - Fixed event propagation for multi-instrument support - Resolved mnq_context.wait_for(EventType.NEW_BAR) functionality ## Bracket Order Enhancements - Changed from price validation failure to automatic alignment - Orders with misaligned prices now auto-correct to tick size - Improved user experience with transparent price handling ## Example Scripts Updates - Fixed all 4 advanced trading examples - Corrected OrderBook API method usage - Fixed real-time data streaming bar access - Updated TypedDict field access patterns ## Test Suite Improvements - Fixed 30 failing tests to match correct behavior - Updated event system tests for forwarding verification - Modified price alignment tests for auto-correction - Added event_bus parameter to InstrumentContext tests ## Documentation - Updated README.md with v3.5.6 features - Added comprehensive CHANGELOG entry - Updated example documentation 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
|
Claude finished @TexasCoding's task —— View job PR Review: v3.5.6 Event System and Bracket Order Fixes✅ Overall Assessment: APPROVEThis PR delivers critical fixes to core functionality with excellent architectural improvements. The changes are well-implemented, thoroughly tested, and maintain backward compatibility. 🎯 Key StrengthsEvent System Improvements
Bracket Order Enhancements
Example Quality
🔍 Technical AnalysisEvent System Architecture# Elegant forwarding implementation
async def forward_to(self, target_bus: "EventBus") -> None:
async def forwarder(event: Event) -> None:
await target_bus.emit(event.type, event.data, event.source)
await self.on_any(forwarder)This is a clean, efficient solution that avoids complex event routing logic. Price Alignment LogicThe automatic price alignment in
Test Coverage
💡 Minor SuggestionsPerformance Considerations
Code Quality Improvements
Documentation
🛡️ Security & Safety Assessment✅ Security Strengths
✅ Financial Safety
📊 Performance ImpactPositive
Negligible Overhead
🧪 Test Strategy ExcellenceThe test suite demonstrates excellent practices:
📋 Compliance CheckRepository Guidelines Adherence
Code Standards
🎯 Final RecommendationAPPROVE - This PR successfully addresses critical functionality gaps while maintaining high code quality standards. The event system fixes enable proper multi-instrument usage, and the bracket order improvements provide better user experience through automatic price alignment. Key Achievements
The implementation is robust, well-tested, and ready for production deployment. |
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Summary
Key Changes
Event System Fixes
on(),once(),off(), andwait_for()methods to InstrumentContextmnq_context.wait_for(EventType.NEW_BAR)Bracket Order Improvements
Example Scripts
Test Suite
Test Results
All tests passing: 3110 passed ✅
Breaking Changes
None - fully backward compatible
🤖 Generated with Claude Code