Skip to content

Commit c4a4a48

Browse files
authored
Merge pull request #9 from TexasCoding/fix_instrument_issue
Fix instrument issue
2 parents f019509 + 111d227 commit c4a4a48

File tree

14 files changed

+497
-59
lines changed

14 files changed

+497
-59
lines changed

CHANGELOG.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,42 @@ All notable changes to the ProjectX Python client will be documented in this fil
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## ⚠️ Development Phase Notice
9+
10+
**IMPORTANT**: This project is under active development. During this phase:
11+
- Breaking changes may be introduced without deprecation warnings
12+
- Backward compatibility is not maintained
13+
- Old implementations are removed when improved
14+
- Clean, modern code architecture is prioritized
15+
16+
## [1.1.3] - 2025-01-29
17+
18+
### Fixed
19+
- **🔧 Contract Selection**: Fixed `_select_best_contract` method to properly handle futures contract naming patterns
20+
- Extracts base symbols by removing month/year suffixes using regex (e.g., NQU5 → NQ, MGCH25 → MGC)
21+
- Handles both single-digit (U5) and double-digit (H25) year codes correctly
22+
- Prevents incorrect matches (searching "NQ" no longer returns "MNQ" contracts)
23+
- Prioritizes exact base symbol matches over symbolId suffix matching
24+
25+
### Added
26+
- **🎮 Interactive Instrument Demo**: New example script for testing instrument search functionality
27+
- `examples/09_get_check_available_instruments.py` - Interactive command-line tool
28+
- Shows the difference between `search_instruments()` (all matches) and `get_instrument()` (best match)
29+
- Visual indicators for active contracts (★) and detailed contract information
30+
- Includes common symbols table and help command
31+
- Continuous search loop for testing multiple symbols
32+
33+
### Enhanced
34+
- **🧪 Test Coverage**: Added comprehensive test suite for contract selection logic
35+
- Tests for exact base symbol matching with various contract patterns
36+
- Tests for handling different year code formats
37+
- Tests for selection priority order (active vs inactive)
38+
- Tests for edge cases (empty lists, no exact matches)
39+
- **📚 Documentation**: Updated README with development phase warnings
40+
- Added prominent development status warning
41+
- Noted that breaking changes may occur without backward compatibility
42+
- Updated changelog format to highlight the development phase
43+
844
## [1.1.2] - 2025-01-28
945

1046
### Enhanced

CLAUDE.md

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,23 @@
22

33
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
44

5+
## Development Phase Guidelines
6+
7+
**IMPORTANT**: This project is in active development. When making changes:
8+
9+
1. **No Backward Compatibility**: Do not maintain old implementations for compatibility
10+
2. **Clean Code Priority**: Always refactor to the cleanest, most modern approach
11+
3. **Remove Legacy Code**: Delete old logic when implementing improvements
12+
4. **Breaking Changes Allowed**: Make breaking changes freely to improve architecture
13+
5. **Modern Patterns**: Use the latest Python patterns and best practices
14+
6. **Simplify Aggressively**: Remove complexity rather than adding compatibility layers
15+
16+
Example approach:
17+
- ❌ DON'T: Keep old method signatures with deprecation warnings
18+
- ✅ DO: Replace methods entirely with better implementations
19+
- ❌ DON'T: Add compatibility shims or adapters
20+
- ✅ DO: Update all callers to use new patterns
21+
522
## Development Commands
623

724
### Package Management (UV)
@@ -160,4 +177,18 @@ data_manager.get_memory_stats() # Real-time data memory
160177
- `max_depth_entries = 1000` (OrderBook depth per side)
161178
- `max_bars_per_timeframe = 1000` (Real-time data per timeframe)
162179
- `tick_buffer_size = 1000` (Tick data buffer)
163-
- `cache_max_size = 100` (Indicator cache entries)
180+
- `cache_max_size = 100` (Indicator cache entries)
181+
182+
## Recent Changes (v1.1.3)
183+
184+
### Contract Selection Fix
185+
The `_select_best_contract` method now properly handles futures contract naming:
186+
- Uses regex to extract base symbols by removing month/year suffixes
187+
- Handles both single-digit (U5) and double-digit (H25) year codes
188+
- Pattern: `^(.+?)([FGHJKMNQUVXZ]\d{1,2})$` where letters are futures month codes
189+
190+
### Interactive Demo
191+
Added `examples/09_get_check_available_instruments.py`:
192+
- Interactive command-line tool for testing instrument search
193+
- Shows difference between `search_instruments()` and `get_instrument()`
194+
- Includes visual indicators and continuous search loop

README.md

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,11 @@ A **high-performance Python SDK** for the [ProjectX Trading Platform](https://ww
2020

2121
This Python SDK acts as a bridge between your trading strategies and the ProjectX platform, handling all the complex API interactions, data processing, and real-time connectivity.
2222

23-
## 📊 SDK Status
23+
## ⚠️ Development Status
2424

25-
**Current Version**: v1.1.2 (Documentation Accuracy & Enhanced Project Structure)
25+
**IMPORTANT**: This project is under active development. New updates may introduce breaking changes without backward compatibility. During this development phase, we prioritize clean, modern code architecture over maintaining legacy implementations.
26+
27+
**Current Version**: v1.1.3 (Contract Selection & Interactive Demo)
2628

2729
**Production Ready SDK Components**:
2830
- Complete ProjectX Gateway API integration with connection pooling
@@ -35,6 +37,8 @@ This Python SDK acts as a bridge between your trading strategies and the Project
3537
- **NEW**: Sub-second response times for cached operations
3638
- **NEW**: Complete TA-Lib overlap indicators (17 total) with full compatibility
3739
- **NEW**: Enhanced indicator discovery and documentation
40+
- **NEW**: Improved futures contract selection with proper suffix handling
41+
- **NEW**: Interactive instrument search demo for testing functionality
3842

3943
🚀 **Performance Highlights**:
4044
- **Connection pooling** reduces API overhead by 50-70%
@@ -427,6 +431,7 @@ The `examples/` directory contains comprehensive demonstrations:
427431
- **`05_orderbook_analysis.py`** - Level 2 market depth analysis
428432
- **`06_multi_timeframe_strategy.py`** - Multi-timeframe trading strategies
429433
- **`07_technical_indicators.py`** - Complete technical analysis showcase
434+
- **`09_get_check_available_instruments.py`** - Interactive instrument search demo
430435

431436
### Example Trading Application Built with the SDK
432437
```python
@@ -606,23 +611,31 @@ We welcome contributions! Please follow these guidelines:
606611

607612
## 📝 Changelog
608613

609-
### Version 1.1.2 (Latest)
610-
**📊 Documentation Accuracy & Enhanced Project Structure**
611-
-**Documentation Alignment**: Updated all documentation to match actual codebase
612-
-**Version Consistency**: Corrected version references throughout project
613-
-**Example Organization**: Updated example file references to match actual structure
614-
-**Project Status Accuracy**: Aligned roadmap and feature status with reality
615-
-**Build on Previous**: Includes all features from v1.0.12:
616-
- **Order-Position Sync**: Automatic synchronization between orders and positions
617-
- **Position Order Tracking**: Orders automatically tracked and associated with positions
618-
- **Comprehensive Test Suite**: 230+ tests covering all major functionality
619-
- **Enhanced Indicators**: 55+ indicators across all categories
614+
### Version 1.1.3 (Latest) - 2025-01-29
615+
**🔧 Contract Selection & Interactive Tools**
616+
617+
**Breaking Changes:**
618+
- ⚠️ **Development Phase**: API changes may occur without deprecation warnings
619+
- ⚠️ **No Backward Compatibility**: Old implementations are removed when improved
620+
621+
**Bug Fixes:**
622+
-**Fixed Contract Selection**: `get_instrument()` now correctly handles futures contract naming patterns
623+
- Properly extracts base symbols by removing month/year suffixes (e.g., NQU5 → NQ, MGCH25 → MGC)
624+
- Prevents incorrect matches (searching "NQ" no longer returns "MNQ" contracts)
625+
- Handles both single-digit (U5) and double-digit (H25) year codes
620626

621627
**New Features:**
622-
- **Bracket Order Integration**: Full lifecycle tracking for entry, stop, and target orders
623-
- **Position Close Handling**: Related orders automatically cancelled when positions close
624-
- **Integration Tests**: End-to-end workflow testing
625-
- **Risk Management Tests**: Comprehensive risk control validation
628+
- **Interactive Instrument Demo**: New example script for testing instrument search functionality
629+
- `examples/09_get_check_available_instruments.py` - Interactive command-line tool
630+
- Shows difference between `search_instruments()` and `get_instrument()` methods
631+
- Visual indicators for active contracts and detailed contract information
632+
633+
**Improvements:**
634+
- **Test Coverage**: Added comprehensive tests for contract selection logic
635+
- **Documentation**: Updated with development phase warnings and breaking change notices
636+
637+
**Includes all features from v1.0.12:**
638+
- Order-Position Sync, Position Order Tracking, 230+ tests, 55+ indicators
626639

627640
### Version 1.0.2-1.0.11
628641
**🚀 Performance & Reliability**

docs/conf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@
2323
project = "project-x-py"
2424
copyright = "2025, Jeff West"
2525
author = "Jeff West"
26-
release = "1.1.2"
27-
version = "1.1.2"
26+
release = "1.1.3"
27+
version = "1.1.3"
2828

2929
# -- General configuration ---------------------------------------------------
3030

docs/index.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ project-x-py Documentation
1919

2020
**project-x-py** is a professional Python SDK for the `ProjectX Trading Platform <https://www.projectx.com/>`_ Gateway API. This library enables developers to build sophisticated trading strategies and applications by providing comprehensive access to futures trading operations, real-time market data, Level 2 orderbook analysis, and a complete technical analysis suite with 55+ TA-Lib compatible indicators.
2121

22+
.. warning::
23+
**Development Phase**: This project is under active development. New updates may introduce breaking changes without backward compatibility. During this development phase, we prioritize clean, modern code architecture over maintaining legacy implementations.
24+
2225
.. note::
2326
**Important**: This is a **client library/SDK**, not a trading strategy. It provides the tools and infrastructure to help developers create their own trading strategies that integrate with the ProjectX platform.
2427

examples/06_multi_timeframe_strategy.py

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@
3232
create_trading_suite,
3333
setup_logging,
3434
)
35+
from project_x_py.models import Order, Position
36+
from project_x_py.order_manager import OrderManager
37+
from project_x_py.position_manager import PositionManager
38+
from project_x_py.realtime_data_manager import ProjectXRealtimeDataManager
3539

3640

3741
class MultiTimeframeStrategy:
@@ -370,14 +374,18 @@ def _emergency_cleanup(signum=None, frame=None):
370374
print("⚠️ Emergency position and order cleanup in progress...")
371375

372376
try:
373-
order_manager = _cleanup_managers.get("order_manager")
374-
position_manager = _cleanup_managers.get("position_manager")
375-
data_manager = _cleanup_managers.get("data_manager")
377+
order_manager: OrderManager | None = _cleanup_managers.get("order_manager")
378+
position_manager: PositionManager | None = _cleanup_managers.get(
379+
"position_manager"
380+
)
381+
data_manager: ProjectXRealtimeDataManager | None = _cleanup_managers.get(
382+
"data_manager"
383+
)
376384

377385
if order_manager and position_manager:
378386
# Get current state
379-
positions = position_manager.get_all_positions()
380-
orders = order_manager.search_open_orders()
387+
positions: list[Position] = position_manager.get_all_positions()
388+
orders: list[Order] = order_manager.search_open_orders()
381389

382390
if positions or orders:
383391
print(
@@ -389,7 +397,7 @@ def _emergency_cleanup(signum=None, frame=None):
389397
try:
390398
order_manager.cancel_order(order.id)
391399
print(f" ✅ Cancelled order {order.id}")
392-
except:
400+
except Exception:
393401
print(f" ❌ Failed to cancel order {order.id}")
394402

395403
# Close all positions with market orders
@@ -405,8 +413,10 @@ def _emergency_cleanup(signum=None, frame=None):
405413
print(
406414
f" ✅ Emergency close order: {close_response.order_id}"
407415
)
408-
except:
409-
print(f" ❌ Failed to close position {pos.contractId}")
416+
except Exception as e:
417+
print(
418+
f" ❌ Failed to close position {pos.contractId}: {e}"
419+
)
410420

411421
print("⏳ Waiting 3 seconds for emergency orders to process...")
412422
time.sleep(3)
@@ -418,8 +428,8 @@ def _emergency_cleanup(signum=None, frame=None):
418428
try:
419429
data_manager.stop_realtime_feed()
420430
print("🧹 Real-time feed stopped")
421-
except:
422-
pass
431+
except Exception as e:
432+
print(f"❌ Error stopping real-time feed: {e}")
423433

424434
except Exception as e:
425435
print(f"❌ Emergency cleanup error: {e}")
@@ -494,9 +504,9 @@ def main():
494504
timeframes=timeframes,
495505
)
496506

497-
data_manager = trading_suite["data_manager"]
498-
order_manager = trading_suite["order_manager"]
499-
position_manager = trading_suite["position_manager"]
507+
data_manager: ProjectXRealtimeDataManager = trading_suite["data_manager"]
508+
order_manager: OrderManager = trading_suite["order_manager"]
509+
position_manager: PositionManager = trading_suite["position_manager"]
500510

501511
# Store managers for emergency cleanup
502512
_cleanup_managers["data_manager"] = data_manager
@@ -603,11 +613,11 @@ def main():
603613
else:
604614
print(" ❌ Signal execution failed")
605615
else:
606-
print(" ℹ️ Signal execution skipped by user")
616+
print(" Signal execution skipped by user")
607617

608618
# Show current positions and orders
609-
positions = position_manager.get_all_positions()
610-
orders = order_manager.search_open_orders()
619+
positions: list[Position] = position_manager.get_all_positions()
620+
orders: list[Order] = order_manager.search_open_orders()
611621

612622
print("\n📊 Current Status:")
613623
print(f" Open Positions: {len(positions)}")
@@ -804,11 +814,11 @@ def main():
804814
if close_response.success:
805815
closed_count += 1
806816
print(
807-
f" ✅ Close order placed: {close_response.order_id}"
817+
f" ✅ Close order placed: {close_response.orderId}"
808818
)
809819
else:
810820
print(
811-
f" ❌ Failed to place close order: {close_response.error_message}"
821+
f" ❌ Failed to place close order: {close_response.errorMessage}"
812822
)
813823

814824
except Exception as e:
@@ -837,7 +847,7 @@ def main():
837847
print(" ✅ All positions successfully closed")
838848
else:
839849
print(
840-
" ℹ️ Cleanup skipped by user - positions and orders remain open"
850+
"Cleanup skipped by user - positions and orders remain open"
841851
)
842852
print(" ⚠️ IMPORTANT: Monitor your positions manually!")
843853
else:

examples/07_technical_indicators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,7 @@ def create_comprehensive_analysis(data):
463463

464464
print("\n📊 Volatility Analysis:")
465465
if bb_lower < price < bb_upper:
466-
print(" ℹ️ Price within Bollinger Bands: Normal")
466+
print(" Price within Bollinger Bands: Normal")
467467
elif price >= bb_upper:
468468
print(" ⚠️ Price at upper BB: Potential reversal")
469469
else:

0 commit comments

Comments
 (0)