Repository navigation
Closed
1 / 21 of 2 issues completedClosed
1 / 21 of 2 issues completed
Copy link
Labels
enhancementNew feature or requestNew feature or requestpipedreamAdvanced future features - ambitious long-term goalsAdvanced future features - ambitious long-term goals
Description
Problem
After human approves trades, need systematic tracking of active positions with automated exit condition monitoring and human alert system.
Dependencies & Relationships
Status: PARTIALLY COMPLETE - Core position management done, exit tracking needs enhancement
Depends on: #258 (Alpaca Integration - ✅ COMPLETE)
Related: #321 (Dynamic Trailing Stops - enhances exit tracking)
Integrates with: #308 (Human-in-Loop CLI)
Current Status
✅ Completed Components
- Position Tracking:
src/trading/position_manager.pyoperational - Real-time P&L: Broker-as-truth reconciliation working
- Order Management:
src/trading/order_manager.pycomplete - Bracket Orders: 8% TP / 5% SL automated via Alpaca OCO legs
🚧 Needs Enhancement
- Dynamic Stop Adjustment: See Implement Dynamic Trailing Stop Logic #321 (Dynamic Trailing Stops)
- Exit Alert System: Human notification for exit conditions
- Position Monitoring Dashboard: Real-time position visualization
Solution: Position Management with Exit Tracking
Manage active positions and generate exit recommendations using validated balanced exit strategy (8% TP / 5% SL).
Requirements
- Track all open positions with real-time P&L calculation
- Monitor for 8% TP / 5% SL levels using validated exit parameters
- Generate exit recommendations when conditions met (enhancement needed)
- Alert human for review before executing exits (integrate with CLI Human-in-Loop Trading Interface - Text-based decision approval #308)
- Log all position lifecycle events for analysis
- Support multiple concurrent positions (implemented)
Position Lifecycle
Entry → Active Monitoring → Exit Trigger → Human Alert → Execute Exit
↓ ↓ ↓ ↓ ↓
[Fill] [Price Tracking] [TP/SL Hit] [Approve/Modify] [Close]
Integration Points
- Position Manager: Core tracking (✅ complete)
- Order Manager: Bracket order placement (✅ complete)
- Trading Cycle: Daily reconciliation (✅ complete)
- CLI Interface (CLI Human-in-Loop Trading Interface - Text-based decision approval #308): Exit decision approval (in development)
- Dynamic Stops (Implement Dynamic Trailing Stop Logic #321): Advanced stop logic (planned)
Deliverables
- Position tracking with broker reconciliation
- Real-time P&L calculation
- Automated TP/SL via bracket orders
- Exit alert system (needs CLI integration CLI Human-in-Loop Trading Interface - Text-based decision approval #308)
- Position monitoring dashboard (future)
- Enhanced stop logic (Implement Dynamic Trailing Stop Logic #321)
Implementation Priority
MEDIUM - Core features complete, enhancements planned
Files Involved
- ✅
src/trading/position_manager.py- Complete - ✅
src/trading/order_manager.py- Complete - ✅
src/trading/trading_cycle.py- Complete - 🚧
src/human_interface/cli_interface.py- Exit alerts (via CLI Human-in-Loop Trading Interface - Text-based decision approval #308) - 🚧
src/trading/dynamic_stops.py- New (via Implement Dynamic Trailing Stop Logic #321)
Success Criteria
- All positions tracked accurately
- Exit conditions monitored in real-time
- Bracket orders execute automatically
- Human receives exit alerts (pending CLI Human-in-Loop Trading Interface - Text-based decision approval #308)
- Dynamic stop adjustment works (pending Implement Dynamic Trailing Stop Logic #321)
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or requestpipedreamAdvanced future features - ambitious long-term goalsAdvanced future features - ambitious long-term goals
Activity
feat: enhance position management with exit alerts and dynamic stop i…
feat: enhance position management with exit alerts and dynamic stop i…
iAmGiG commentedon Nov 11, 2025
✅ Implementation Complete
Position management enhancements have been implemented and merged into
feature/position-management-enhancementsbranch.What Was Delivered
New Alert System:
Enhanced Features:
Files Modified:
src/trading_tools/position_tracker.py(+301 lines)src/trading/trading_cycle.py(+216 lines)main.py(alert checking integration)docs/position_management_enhancements.md(complete documentation)Testing Results
✅ PositionTracker initializes successfully
✅ Alert methods exist and are callable
✅ Integration with trading_cycle complete
✅ Alert summary functionality working
Benefits
Next Steps
iAmGiG commentedon Nov 11, 2025
Branch Review: feature/position-management-enhancements ✅
Implementation Summary
Branch adds exit alert system and enhanced stop adjustment logging to position management.
1. Exit Alert System
New Components (
src/trading_tools/position_tracker.py):Alert Types:
APPROACHING_TAKE_PROFIT- Within 2% of TP targetAPPROACHING_STOP_LOSS- Within 2% of SL levelSTOP_ADJUSTED- Stop order modifiedPROFIT_TARGET_REACHED- TP level hitLOSS_THRESHOLD_REACHED- SL level hitAlert Features:
Example Output:
2. Dynamic Stop Integration
Enhanced (
src/trading/trading_cycle.py):Progressive Stop Adjustment:
Detailed Logging:
Example Log:
3. Trading Cycle Integration
Modified (
main.py,src/trading/trading_cycle.py):New Workflow Step:
New Method:
Files Changed
docs/position_management_enhancements.md(+243 lines) - Documentationmain.py(+11 lines) - Alert display integrationsrc/trading/trading_cycle.py(+216 lines) - Enhanced stop logic, alert checkingsrc/trading_tools/position_tracker.py(+301 lines) - Alert system implementationTotal: 710 insertions, 61 deletions
What This Delivers
✅ Real-time position alerts - Know when exits are approaching
✅ Smart alert cooldown - No spam from price fluctuations
✅ Alert history - Track all alerts per position
✅ Enhanced logging - Debug stop adjustments easily
✅ Progressive stops - Validated exit strategy automated
What's Still Pending (per issue description)
Testing Needed
Ready for Review
Branch is ready for merge pending:
Will hold merge until all 3 branches reviewed for conflicts.
iAmGiG commentedon Nov 11, 2025
Documentation Updated ✅
Added comprehensive documentation addressing how alerts work:
New Sections Added
1. How Alerts Are Triggered:
python main.py paper-trade SYMBOL2. Alert Output Locations:
logs/trading.log)3. Alert Execution Flow:
4. Alert Frequency & Cooldown:
5. Limitations & Recommendations:
6. Expanded Future Enhancements:
Documentation File
docs/position_management_enhancements.mdnow fully documents:Key Clarifications
Alert Triggering:
No External Notifications:
Trade-off Explanation:
Commit:
931cf42feat: persist alert history across restarts
iAmGiG commentedon Nov 11, 2025
Quick Win Implemented: Alert History Persistence ✅
Problem Solved
Before: Alert history lost on restart
After: Alert history persists across restarts
Implementation
Commit:
45e734dNew Methods in
PositionTracker1. Serialization:
2. Deserialization:
Updated
CostEfficientTradeCycleSave on every state update:
Restore on startup:
Example
local_state.json{ "positions": { "TQQQ": { "entry_price": 50.0, "quantity": 100, "stop_price": 47.50, "target_price": 54.00 } }, "position_tracker_state": { "alert_counter": 5, "config": { "take_profit_pct": 0.08, "stop_loss_pct": 0.05, "alert_cooldown_seconds": 300 }, "positions": { "TQQQ_50.0": { "position_id": "TQQQ_50.0", "ticker": "TQQQ", "entry_price": 50.0, "alert_history": [ { "alert_id": "alert_TQQQ_1", "alert_type": "approaching_tp", "timestamp": "2025-01-10T14:30:00", "current_price": 53.85, "severity": "WARNING", "details": {"distance_pct": 1.85} }, { "alert_id": "alert_TQQQ_2", "alert_type": "approaching_tp", "timestamp": "2025-01-10T14:35:01", "current_price": 53.92, "severity": "WARNING", "details": {"distance_pct": 0.92} } ], "last_alert_time": "2025-01-10T14:35:01" } } }, "last_update": "2025-01-10T15:50:00" }Benefits
✅ Alert history survives restarts - No data loss
✅ Cooldown persists across sessions - No alert spam after restart
✅ Post-trade analysis - Can review alert patterns
✅ No additional API calls - Uses local state only
✅ Complete audit trail - Every alert ever generated is saved
✅ Backward compatible - Gracefully handles missing tracker state
Testing Results
Roundtrip serialization:
✅ Serialized tracker Positions: 1 Alert counter: 1 Alert history entries: 1 ✅ Restored to new tracker Restored positions: 1 Restored alerts: 1Cooldown persistence:
Next Optimization Opportunities
Based on user feedback, there are additional optimization opportunities to explore:
1. Broker State Caching
Idea: Cache
fetch_broker_state()results for 60 secondsBenefit: Reduce API calls in multi-command sessions
Savings: 33-50% API calls in interactive use
2. Piggyback Position Updates
Idea: First API call in session also updates alerts in background
Benefit: Fresh alerts without dedicated check
Pattern: "Smuggle" alert check into regular broker fetch
3. Background Alert Refresh
Idea: Long-running sessions auto-refresh alerts every 5 minutes
Benefit: Always-fresh alerts without manual trigger
Use case: Daemon mode, CLI tool sessions
These warrant separate issues/PRs for focused implementation.
Files Modified
src/trading_tools/position_tracker.py(+68 lines)to_dict()serializationrestore_from_dict()deserializationsrc/trading/trading_cycle.py(+18 lines)save_local_state()to persist trackerload_local_state()to restore trackerTotal: +86 insertions, -3 deletions
Closes the "alert caching" gap - alerts now persist permanently.
merge: integrate position management enhancements with alert system (#…
feat: unified interactive CLI with alerts, scheduler, and portfolio (#…
feat: make unified CLI the default entry point (#339)
iAmGiG commentedon Nov 11, 2025
✅ Merged into DocsGroomingAndReview
Branch:
feature/position-management-enhancementsStatus: Fully merged, tested, and enhanced ✅
Local branch: Deleted (no longer needed)
Merge Details
Commits merged:
817048d- feat: enhance position management with exit alerts and dynamic stop integration (Position Management with Exit Tracking - Active position monitoring #306)931cf42- docs: clarify alert triggering, output locations, and limitations45e734d- feat: persist alert history across restartsMerged via:
947baf4- merge: integrate position management enhancements with alert system (Position Management with Exit Tracking - Active position monitoring #306)1451595- merge: integrate YAML prompts, position alerts, and GTC scheduler into unified systemFinal location: DocsGroomingAndReview branch
What Was Implemented
Core Alert System:
✅ 5 alert types (approaching TP/SL, stop adjusted, targets reached)
✅ 3 severity levels (INFO, WARNING, CRITICAL)
✅ 5-minute cooldown to prevent spam
✅ Alert history tracking
✅ Progressive stop adjustment logic
Enhancements Added:
✅ Alert persistence - Survives restarts via
to_dict()/restore_from_dict()✅ Comprehensive docs - 418 lines in
docs/position_management_enhancements.md✅ Integrated into unified CLI - "check my alerts" command (#339)
Files Modified:
src/trading_tools/position_tracker.py(+371 lines)src/trading/trading_cycle.py(+235 lines)docs/position_management_enhancements.md(new, 418 lines)main.py(+11 lines)Integration with Unified CLI (#339)
Alerts now accessible via interactive CLI:
Testing
✅ Serialization roundtrip verified
✅ Alert cooldown working
✅ Integration with trading_cycle tested
✅ CLI routing functional
Feature Branch Cleanup
Local branch deleted:
git branch -d feature/position-management-enhancementsRemote branch remains for reference:
origin/feature/position-management-enhancementsThis feature is production-ready and fully integrated into the unified system!
iAmGiG commentedon Nov 11, 2025
🧹 Remote Branch Cleanup
Branch:
origin/feature/position-management-enhancementsStatus: Fully merged into DocsGroomingAndReview ✅
Action: Remote branch will be deleted (already merged)
This branch served its purpose:
947baf401_position_alerts_system.mdNo PR needed - feature already integrated and tested.
docs: organize feature documentation as user manual (#328 #306 #287 #339
feat(cache): implement SQLite-based cache system (issue #336)
feat(cache): implement SQLite-based cache system (issue #336)