Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
b3c1a89
test: add comprehensive tests for exceptions module (100% coverage)
TexasCoding Aug 25, 2025
3edb96d
test: add comprehensive tests for config module (94% coverage)
TexasCoding Aug 25, 2025
583bed9
test: add comprehensive tests for order_templates module (97% coverage)
TexasCoding Aug 25, 2025
f46ec13
test: add comprehensive tests for utils modules (86-100% coverage)
TexasCoding Aug 25, 2025
619bbad
chore: update dependencies and fix data_utils import
TexasCoding Aug 25, 2025
89bf2f8
test: add comprehensive tests for order_manager module (69% coverage)
TexasCoding Aug 25, 2025
f96244d
test: fix order_manager test failures (reduce from 39 to 33)
TexasCoding Aug 25, 2025
0a9efd9
fix: critical bracket order bugs and comprehensive test fixes
TexasCoding Aug 25, 2025
4675aac
test: add comprehensive coverage for bracket_orders.py emergency scen…
TexasCoding Aug 25, 2025
f9ba948
update claude.md
TexasCoding Aug 25, 2025
2673c5b
test: add comprehensive tests for position_manager risk and reporting…
TexasCoding Aug 25, 2025
04e9116
test: complete position_manager core testing with 100% pass rate
TexasCoding Aug 26, 2025
d046cb8
fix: remove non-existent subscription method calls from tracking.py
TexasCoding Aug 26, 2025
3b328c1
fix: resolve all failing tests in test_tracking_comprehensive.py
TexasCoding Aug 26, 2025
5e7e334
fix: realtime.core module - fix URL priority and test alignment
TexasCoding Aug 26, 2025
ecaf773
test: add comprehensive tests for realtime event_handling module
TexasCoding Aug 26, 2025
3b1c216
fix: critical bug in event_handling.py - _trigger_callbacks now updat…
TexasCoding Aug 26, 2025
9b62248
test: add comprehensive tests for subscriptions.py module (33 tests)
TexasCoding Aug 26, 2025
83ca296
test: comprehensive testing of realtime_data_manager module
TexasCoding Aug 26, 2025
3d51d32
test: comprehensive risk_manager module testing with 100% pass rate
TexasCoding Aug 27, 2025
4638ec0
tweaked examples
TexasCoding Aug 27, 2025
5324426
test: comprehensive orderbook module testing with 154 tests passing a…
TexasCoding Aug 27, 2025
53ffd8b
fix: resolve all type checking and linting issues in order_manager mo…
TexasCoding Aug 28, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .claude/commands/test-module.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
## Objective:

Your primary goal is to develop a comprehensive test suite for the src/project_x_py/{{module}}/ module, ensuring its logic is robust and correct. You will strictly adhere to the project's Test-Driven
Development (TDD) methodology.

## Core Instructions:

1. **Understand the Framework**: Begin by thoroughly reading CLAUDE.md. This document contains critical information about the project's architecture, coding standards, and the TDD principles we adhere to. Pay close
attention to the TDD section, as it is the foundation for this task.

2. **Review Proven Patterns**: Access and apply our established TDD development pattern from your memory. This pattern dictates that tests are written before the implementation and serve as the ultimate
specification for the code's behavior.

3. **Assess Current Status**: Read the v3.3.6 Testing Summary to get a clear picture of the current testing landscape for the {{module}} module. This will help you identify areas that are untested or need more
thorough validation.

4. **TDD for `{{module}}`**:
* Audit Existing Tests: Before writing new tests, critically evaluate any existing tests for the {{module}}. Your audit must confirm that they are testing for the correct behavior and not simply mirroring
flawed logic in the current implementation.
* Follow the TDD Cycle: For all new tests, you must follow the **Red-Green-Refactor cycle**:
1. Red: Write a failing test that defines the desired functionality.
2. Green: Write the minimal code necessary to make the test pass.
3. Refactor: Improve the code's design and quality while ensuring all tests remain green.
* **Bug Discovery**: The primary goal of this TDD approach is to uncover any bugs in the core logic. If a test fails, it is because the implementation is incorrect, not the test. Fix the code to match the
test's expectations.

## Final Deliverable:

A complete set of tests for the src/project_x_py/{{module}}/ module that provides full coverage and validates the correctness of its logic. This test suite will serve as the definitive specification for the
module's behavior.
38 changes: 11 additions & 27 deletions .mcp.json
Original file line number Diff line number Diff line change
@@ -1,33 +1,21 @@
{
"mcpServers": {
"upstash-context-7-mcp": {
"type": "http",
"url": "https://server.smithery.ai/@upstash/context7-mcp/mcp"
},
"aakarsh-sasi-memory-bank-mcp": {
"type": "http",
"url": "https://server.smithery.ai/@aakarsh-sasi/memory-bank-mcp/mcp"
},
"itseasy-21-mcp-knowledge-graph": {
"type": "http",
"url": "https://server.smithery.ai/@itseasy21/mcp-knowledge-graph/mcp"
"desktop-commander": {
"command": "npx",
"args": [
"-y",
"@wonderwhy-er/desktop-commander"
]
},
"smithery-ai-filesystem": {
"type": "stdio",
"github": {
"command": "npx",
"args": [
"-y",
"@smithery/cli@latest",
"run",
"@smithery-ai/filesystem",
"--profile",
"yummy-owl-S0TDf6",
"--key",
"af08fae1-5f3a-43f6-9e94-86f9638a08a0",
"--config",
"\"{\\\"allowedDirs\\\":[\\\"src\\\",\\\"examples\\\",\\\"tests\\\"]}\""
"@modelcontextprotocol/server-github"
],
"env": {}
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_PERSONAL_ACCESS_TOKEN}"
}
},
"project-x-py Docs": {
"command": "npx",
Expand Down Expand Up @@ -57,10 +45,6 @@
"TAVILY_API_KEY": "${TAVILY_API_KEY}"
}
},
"waldzellai-clear-thought": {
"type": "http",
"url": "https://server.smithery.ai/@waldzellai/clear-thought/mcp"
},
"graphiti-memory": {
"transport": "stdio",
"command": "/Users/jeffreywest/.local/bin/uv",
Expand Down
100 changes: 100 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,106 @@ The standardized deprecation utilities provide:
- Metadata tracking for deprecation management
- Support for functions, methods, classes, and parameters

## Test-Driven Development (TDD) Methodology

**CRITICAL**: This project follows strict Test-Driven Development principles. Tests define the specification, not the implementation.

### Core TDD Rules

1. **Write Tests FIRST**
- Tests must be written BEFORE implementation code
- Tests define the contract/specification of how code should behave
- Follow Red-Green-Refactor cycle religiously

2. **Tests as Source of Truth**
- Tests validate EXPECTED behavior, not current behavior
- If existing code fails a test, FIX THE CODE, not the test
- Tests document how the system SHOULD work
- Never write tests that simply match faulty logic

3. **Red-Green-Refactor Cycle**
```
1. RED: Write a failing test that defines expected behavior
2. GREEN: Write minimal code to make the test pass
3. REFACTOR: Improve code while keeping tests green
4. REPEAT: Continue for next feature/requirement
```

4. **Testing Existing Code**
- Treat tests as debugging tools
- Write tests for what the code SHOULD do, not what it currently does
- If tests reveal bugs, fix the implementation
- Only modify tests if requirements have genuinely changed

5. **Test Writing Principles**
- Each test should have a single, clear purpose
- Test outcomes and behavior, not implementation details
- Tests should be independent and isolated
- Use descriptive test names that explain the expected behavior

### Example TDD Workflow

```python
# Step 1: Write the test FIRST (Red phase)
@pytest.mark.asyncio
async def test_order_manager_places_bracket_order():
"""Test that bracket orders create parent, stop, and target orders."""
# Define expected behavior
order_manager = OrderManager(mock_client)

result = await order_manager.place_bracket_order(
instrument="MNQ",
quantity=1,
stop_offset=10,
target_offset=20
)

# Assert expected outcomes
assert result.parent_order is not None
assert result.stop_order is not None
assert result.target_order is not None
assert result.stop_order.price == result.parent_order.price - 10
assert result.target_order.price == result.parent_order.price + 20

# Step 2: Run test - it SHOULD fail (Red confirmed)
# Step 3: Implement minimal code to pass (Green phase)
# Step 4: Refactor implementation while keeping test green
# Step 5: Write next test for edge cases
```

### Testing as Debugging

When testing existing code:
```python
# WRONG: Writing test to match buggy behavior
def test_buggy_calculation():
# This matches what the code currently does (wrong!)
assert calculate_risk(100, 10) == 1100 # Bug: should be 110

# CORRECT: Write test for expected behavior
def test_risk_calculation():
# This defines what the code SHOULD do
assert calculate_risk(100, 10) == 110 # 10% of 100 is 10, total 110
# If this fails, FIX calculate_risk(), don't change the test
```

### Test Organization

- `tests/unit/` - Fast, isolated unit tests (mock all dependencies)
- `tests/integration/` - Test component interactions
- `tests/e2e/` - End-to-end tests with real services
- Always run tests with `./test.sh` for proper environment setup

### TDD Benefits for This Project

1. **API Stability**: Tests ensure backward compatibility
2. **Async Safety**: Tests catch async/await issues early
3. **Financial Accuracy**: Tests validate pricing and calculations
4. **Documentation**: Tests serve as living documentation
5. **Refactoring Confidence**: Tests enable safe refactoring

Remember: The test suite is the specification. Code must conform to tests, not vice versa.

## Specialized Agent Usage Guidelines

### IMPORTANT: Use Appropriate Subagents for Different Tasks
Expand Down
88 changes: 88 additions & 0 deletions CRITICAL_BUGS_FOUND.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Critical Bugs Found During Testing - 2025-08-25

## STATUS: ✅ FIXED - 2025-08-24

All critical bugs have been successfully fixed and tested in the bracket_orders.py module.

### Fixes Applied:
1. **Unprotected Position Risk**: Added emergency position closure when protective orders fail
2. **Input Validation**: Added proper validation for entry_type and entry_price parameters
3. **Recovery Manager**: Fixed attribute access (getattr instead of direct access)
4. **Type Safety**: Fixed entry_price type handling for market orders (None -> 0.0)
5. **Code Quality**: Resolved all IDE diagnostics errors

### Test Results:
- 11 tests passing (up from 8)
- 3 critical bugs fixed (were xfail, now pass)
- 1 xfail remaining (mock-specific issue, not production bug)

## 1. CRITICAL: Unprotected Position Risk [✅ FIXED]
**File**: `src/project_x_py/order_manager/bracket_orders.py`
**Severity**: CRITICAL - Financial Risk
**Test**: `test_bracket_orders.py::test_bracket_order_emergency_close_on_failure`

### Issue
When protective orders (stop loss and take profit) fail to place after a bracket order entry is filled, the system returns success and leaves the position completely unprotected. This exposes traders to unlimited financial risk.

### Current Behavior
- Entry order fills successfully
- Stop loss order fails to place
- Take profit order fails to place
- Method returns `BracketOrderResponse(success=True, stop_order_id=None, target_order_id=None)`
- Position remains open with NO risk management

### Expected Behavior
- When protective orders fail, immediately close the position
- Raise `ProjectXOrderError` with clear message about unprotected position
- Log emergency closure attempt
- Return failure status to prevent false confidence

### Impact
Traders believe they have a protected position when they actually have unlimited risk exposure.

## 2. Recovery Manager Integration Broken
**File**: `src/project_x_py/order_manager/bracket_orders.py`
**Test**: `test_bracket_orders.py::test_bracket_order_with_recovery_manager`

### Issue
The `_get_recovery_manager()` method is called but doesn't properly access the recovery_manager attribute, preventing transaction rollback on failures.

### Current Behavior
- Code calls `self._get_recovery_manager()` at line 250
- Method exists at line 124 but doesn't access `self.recovery_manager`
- Recovery operations are never tracked

### Expected Behavior
- Recovery manager should track all bracket order operations
- Failed operations should trigger automatic rollback
- Partial failures should be recoverable

## 3. Missing Input Validation
**File**: `src/project_x_py/order_manager/bracket_orders.py`
**Tests**:
- `test_bracket_orders.py::test_bracket_order_invalid_entry_type`
- `test_bracket_orders.py::test_bracket_order_missing_entry_price_for_limit`

### Issues
1. No validation for `entry_type` parameter - accepts any string value
2. No validation for `None` entry_price - causes Decimal conversion error

### Current Behavior
- Any non-"market" entry_type is treated as "limit" (including invalid values)
- `None` entry_price causes `decimal.ConversionSyntax` error instead of validation error

### Expected Behavior
- Validate entry_type is only "market" or "limit"
- Validate entry_price is not None for limit orders
- Raise clear `ProjectXOrderError` with descriptive messages

## Recommendations

1. **IMMEDIATE**: Fix the unprotected position bug - this is a critical financial risk
2. **HIGH PRIORITY**: Fix recovery manager integration for proper transaction semantics
3. **MEDIUM**: Add input validation to prevent confusing errors

## Test Status
- 8 tests passing (correct behavior)
- 4 tests marked as xfail (documenting bugs)
- All tests properly reflect expected behavior, not current bugs
65 changes: 65 additions & 0 deletions ORDER_MANAGER_FIXES_SUMMARY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Order Manager Testing & Bug Fixes Summary

## Date: 2025-08-24

### Critical Bugs Fixed

1. **Unprotected Position Risk** (bracket_orders.py:566-587)
- **Issue**: When protective orders failed after entry fill, the system would leave positions unprotected
- **Fix**: Added emergency position closure when both stop and target orders fail
- **Impact**: Prevents catastrophic losses from unprotected positions

2. **Recovery Manager Integration** (bracket_orders.py:769-776)
- **Issue**: `_get_recovery_manager()` method didn't properly access the recovery_manager attribute
- **Fix**: Updated to check both `_recovery_manager` and `recovery_manager` attributes using getattr
- **Impact**: Enables proper transaction-like semantics for bracket orders

3. **Input Validation** (bracket_orders.py:305-315)
- **Issue**: No validation for entry_type parameter and None entry_price
- **Fix**: Added validation to ensure entry_type is 'market' or 'limit', and entry_price is required for limit orders
- **Impact**: Prevents runtime errors from invalid input

### Test Suite Improvements

#### Tests Fixed
- ✅ **error_recovery.py**: 51 tests passing (fixed OrderPlaceResponse instantiation)
- ✅ **tracking.py**: 62 tests passing (fixed incomplete Order model data)
- ✅ **bracket_orders.py**: 12 tests passing (comprehensive test coverage)
- ✅ **core.py**: 30 tests passing
- ✅ **order_types.py**: 6 tests passing
- ✅ **position_orders.py**: 20 tests passing

#### Test Cleanup
- Removed `test_bracket_orders_old.py` (duplicate tests)
- Fixed test data issues (missing required fields in Order and OrderPlaceResponse models)
- Updated test expectations to match corrected behavior

### Code Changes

#### src/project_x_py/order_manager/bracket_orders.py
- Lines 305-315: Added entry_type and entry_price validation
- Lines 421-423: Added account_id parameter passing to cancel_order
- Lines 566-587: Added emergency position closure logic
- Lines 769-776: Fixed recovery manager access

#### Test Files Modified
- tests/order_manager/test_error_recovery.py: Fixed OrderPlaceResponse instantiations
- tests/order_manager/test_tracking.py: Added complete Order model data
- tests/order_manager/test_bracket_orders.py: Updated for new validation and error handling

### Backward Compatibility
All changes maintain backward compatibility:
- Optional parameters default to None
- Existing API signatures unchanged
- Error handling preserves existing exception types

### Final Test Results
```
196 tests collected
195 passed
1 xfailed (known issue with recovery manager mock)
0 failed
```

## Conclusion
Successfully identified and fixed 3 critical bugs in the order manager's bracket order implementation. All tests are now passing, and the system properly handles edge cases that could lead to unprotected positions or runtime errors.
Loading
Loading