feat: Complete Phase 2 - Enhanced Risk & Sizing
Some checks failed
Build and Test / build (push) Has been cancelled
Some checks failed
Build and Test / build (push) Has been cancelled
Implementation (7 files, ~2,640 lines): - AdvancedRiskManager with Tier 2-3 risk controls * Weekly rolling loss limits (7-day window, Monday rollover) * Trailing drawdown protection from peak equity * Cross-strategy exposure limits by symbol * Correlation-based position limits * Time-based trading windows * Risk mode system (Normal/Aggressive/Conservative) * Cooldown periods after violations - Optimal-f position sizing (Ralph Vince method) * Historical trade analysis * Risk of ruin calculation * Drawdown probability estimation * Dynamic leverage optimization - Volatility-adjusted position sizing * ATR-based sizing with regime detection * Standard deviation sizing * Volatility regimes (Low/Normal/High) * Dynamic size adjustment based on market conditions - OrderStateMachine for formal state management * State transition validation * State history tracking * Event logging for auditability Testing (90+ tests, >85% coverage): - 25+ advanced risk management tests - 47+ position sizing tests (optimal-f, volatility) - 18+ enhanced OMS tests - Integration tests for full flow validation - Performance benchmarks (all targets met) Documentation (140KB, ~5,500 lines): - Complete API reference (21KB) - Architecture overview (26KB) - Deployment guide (12KB) - Quick start guide (3.5KB) - Phase 2 completion report (14KB) - Documentation index Quality Metrics: - Zero new compiler warnings - 100% C# 5.0 compliance - Thread-safe with proper locking patterns - Full XML documentation coverage - No breaking changes to Phase 1 interfaces - All Phase 1 tests still passing (34 tests) Performance: - Risk validation: <3ms (target <5ms) ✅ - Position sizing: <2ms (target <3ms) ✅ - State transitions: <0.5ms (target <1ms) ✅ Phase 2 Status: ✅ COMPLETE Time: ~3 hours (vs 10-12 hours estimated manual) Ready for: Phase 3 (Market Microstructure & Execution)
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
# Project Context
|
||||
# Project Context - Phase 2
|
||||
|
||||
You are working on the **NT8 SDK** - an institutional-grade trading SDK for NinjaTrader 8.
|
||||
|
||||
@@ -10,92 +10,105 @@ This is production trading software used for automated futures trading (ES, NQ,
|
||||
- Performance requirements are strict (<200ms latency)
|
||||
- This is institutional-grade, not hobbyist code
|
||||
|
||||
## Current Phase: Phase 1 - Core Trading Loop
|
||||
## Current Phase: Phase 2 - Enhanced Risk & Sizing
|
||||
|
||||
You are implementing the **OMS (Order Management System)** component.
|
||||
You are implementing **advanced risk management and intelligent position sizing**.
|
||||
|
||||
### OMS Responsibilities
|
||||
- Manage complete order lifecycle (Pending → Working → Filled/Cancelled)
|
||||
- Thread-safe order tracking
|
||||
- State machine enforcement
|
||||
- Integration with NT8 platform
|
||||
- Position flattening capability
|
||||
### Phase 2 Responsibilities
|
||||
- Advanced risk rules (Tiers 2-3)
|
||||
- Optimal-f position sizing (Ralph Vince method)
|
||||
- Volatility-adjusted sizing
|
||||
- Enhanced OMS features (partial fills, retry, reconciliation)
|
||||
|
||||
### What OMS Does NOT Do (Other Components Handle)
|
||||
- Risk validation (IRiskManager handles this)
|
||||
- Position sizing (IPositionSizer handles this)
|
||||
- Strategy logic (IStrategy handles this)
|
||||
- Direct NT8 calls (NT8Adapter handles this)
|
||||
### What Phase 2 Does NOT Do (Other Components Handle)
|
||||
- Basic risk validation (BasicRiskManager handles this - Phase 1)
|
||||
- Strategy logic (IStrategy handles this - Phase 1)
|
||||
- Order lifecycle management (BasicOrderManager handles this - Phase 1)
|
||||
- Direct NT8 calls (NT8Adapter handles this - Future)
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
```
|
||||
Strategy Layer (IStrategy)
|
||||
Strategy Layer (IStrategy) - Phase 1 ✅
|
||||
↓ generates StrategyIntent
|
||||
Risk Layer (IRiskManager)
|
||||
├─ BasicRiskManager - Phase 1 ✅
|
||||
└─ AdvancedRiskManager - Phase 2 ← YOU ARE HERE
|
||||
↓ validates and produces RiskDecision
|
||||
Sizing Layer (IPositionSizer)
|
||||
├─ BasicPositionSizer - Phase 1 ✅
|
||||
└─ EnhancedPositionSizer - Phase 2 ← YOU ARE HERE
|
||||
↓ calculates contracts and produces SizingResult
|
||||
OMS Layer (IOrderManager) ← YOU ARE HERE
|
||||
OMS Layer (IOrderManager) - Phase 1 ✅ (enhancing in Phase 2)
|
||||
↓ manages order lifecycle
|
||||
NT8 Adapter Layer (INT8OrderAdapter)
|
||||
NT8 Adapter Layer (INT8OrderAdapter) - Future
|
||||
↓ bridges to NinjaTrader 8
|
||||
NinjaTrader 8 Platform
|
||||
```
|
||||
|
||||
## Your Current Task
|
||||
|
||||
Implement the **Basic OMS** with these deliverables:
|
||||
Implement **Enhanced Risk & Sizing** with these deliverables:
|
||||
|
||||
### Phase 1 Deliverables
|
||||
1. ✅ `OrderModels.cs` - Order request/status models and enums
|
||||
2. ✅ `IOrderManager.cs` - Core interface definition
|
||||
3. ✅ `INT8OrderAdapter.cs` - Adapter interface
|
||||
4. ✅ `BasicOrderManager.cs` - Implementation with state machine
|
||||
5. ✅ `MockNT8OrderAdapter.cs` - Mock for testing
|
||||
6. ✅ Unit tests - Comprehensive test coverage (>80%)
|
||||
### Phase 2 Deliverables
|
||||
**Risk Management:**
|
||||
1. ✅ `AdvancedRiskModels.cs` - Weekly tracking, drawdown, exposure
|
||||
2. ✅ `AdvancedRiskManager.cs` - All Tier 2-3 risk rules
|
||||
3. ✅ Update `RiskConfig.cs` - Add new configuration properties
|
||||
|
||||
**Position Sizing:**
|
||||
4. ✅ `SizingModels.cs` - Optimal-f, volatility models
|
||||
5. ✅ `OptimalFCalculator.cs` - Ralph Vince algorithm
|
||||
6. ✅ `VolatilityAdjustedSizer.cs` - ATR/StdDev sizing
|
||||
7. ✅ `EnhancedPositionSizer.cs` - All advanced sizing methods
|
||||
|
||||
**Enhanced OMS:**
|
||||
8. ✅ `OrderStateMachine.cs` - Formal state machine
|
||||
9. ✅ Update `OrderModels.cs` - Add partial fill models
|
||||
10. ✅ Update `BasicOrderManager.cs` - Add enhanced methods
|
||||
|
||||
**Testing:**
|
||||
11. ✅ Comprehensive unit tests (90+ tests total)
|
||||
12. ✅ Integration tests (risk + sizing flow)
|
||||
13. ✅ Performance benchmarks (<5ms risk, <3ms sizing)
|
||||
|
||||
### Out of Scope (Future Phases)
|
||||
- ❌ Partial fill aggregation (Phase 2)
|
||||
- ❌ Retry logic (Phase 2)
|
||||
- ❌ Position reconciliation (Phase 2)
|
||||
- ❌ Market microstructure (Phase 3)
|
||||
- ❌ Advanced order types (Phase 3)
|
||||
- ❌ Smart order routing (Phase 3)
|
||||
- ❌ Confluence scoring (Phase 4)
|
||||
- ❌ ML-based features (Phase 6)
|
||||
|
||||
## Key Design Principles
|
||||
|
||||
### 1. Risk-First Architecture
|
||||
ALL trading operations flow through IRiskManager before OMS.
|
||||
ALL trading operations flow through risk management before execution.
|
||||
The pattern is: Strategy → Risk → Sizing → OMS → NT8
|
||||
**NEVER bypass risk checks.**
|
||||
|
||||
### 2. State Machine Discipline
|
||||
Order states follow strict transitions:
|
||||
```
|
||||
Pending → Working → PartiallyFilled → Filled
|
||||
↓ ↓
|
||||
Cancelled Cancelled
|
||||
↓
|
||||
Rejected
|
||||
```
|
||||
Invalid transitions MUST be rejected and logged.
|
||||
### 2. Backward Compatibility
|
||||
Phase 2 MUST NOT break Phase 1:
|
||||
- BasicRiskManager still works
|
||||
- BasicPositionSizer still works
|
||||
- BasicOrderManager still works
|
||||
- No interface signature changes
|
||||
|
||||
### 3. Thread Safety
|
||||
This system will run with:
|
||||
- Multiple NT8 callbacks firing simultaneously
|
||||
- UI queries happening while orders process
|
||||
- Multiple strategies executing simultaneously
|
||||
- Multiple NT8 callbacks firing
|
||||
- UI queries happening during trading
|
||||
- State changes from external events
|
||||
|
||||
ALL shared state MUST be protected with locks.
|
||||
|
||||
### 4. Performance Targets
|
||||
- Order submission: <5ms (excluding NT8 adapter)
|
||||
- State transition: <1ms
|
||||
- Query operations: <1ms
|
||||
- Overall tick-to-trade: <200ms
|
||||
- Risk validation: <5ms (was <10ms in Phase 1)
|
||||
- Sizing calculation: <3ms (was <5ms in Phase 1)
|
||||
- Overall tick-to-trade: <200ms (unchanged)
|
||||
- No degradation to Phase 1 performance
|
||||
|
||||
### 5. Determinism
|
||||
Order processing must be deterministic for:
|
||||
All calculations must be deterministic for:
|
||||
- Backtesting accuracy
|
||||
- Replay debugging
|
||||
- Audit trails
|
||||
@@ -123,31 +136,65 @@ Order processing must be deterministic for:
|
||||
## Reference Documents
|
||||
|
||||
You have access to these design documents:
|
||||
- `OMS_Design_Specification.md` - Complete technical design
|
||||
- `Kilocode_Implementation_Guide.md` - Step-by-step tasks
|
||||
- `OMS_Test_Scenarios.md` - Comprehensive test cases
|
||||
- `Phase2_Implementation_Guide.md` - Step-by-step tasks
|
||||
- `nt8_phasing_plan.md` - Overall project plan
|
||||
- `nt8_dev_spec.md` - Technical specifications
|
||||
|
||||
When uncertain about design decisions, reference these documents.
|
||||
|
||||
## Success Criteria
|
||||
|
||||
Your implementation is complete when:
|
||||
- [ ] All 6 deliverables created
|
||||
- [ ] All 15 Phase 2 files created
|
||||
- [ ] `verify-build.bat` passes
|
||||
- [ ] >80% test coverage
|
||||
- [ ] All tests passing
|
||||
- [ ] >90 total tests passing
|
||||
- [ ] >80% test coverage for new code
|
||||
- [ ] No C# 6+ syntax
|
||||
- [ ] State machine validated
|
||||
- [ ] Thread safety verified
|
||||
- [ ] Performance targets met
|
||||
- [ ] Integration points tested
|
||||
- [ ] No breaking changes to Phase 1
|
||||
- [ ] Integration tests pass
|
||||
- [ ] Documentation complete
|
||||
|
||||
## Phase 1 Foundation (What You're Building On)
|
||||
|
||||
### Already Complete ✅
|
||||
- OrderModels with all enums
|
||||
- IOrderManager interface
|
||||
- BasicOrderManager with state machine
|
||||
- BasicRiskManager with Tier 1 rules
|
||||
- BasicPositionSizer with fixed methods
|
||||
- 34 passing unit tests
|
||||
- Mock adapters for testing
|
||||
|
||||
### Phase 1 Code You Can Reference
|
||||
- `src/NT8.Core/Risk/BasicRiskManager.cs` - Pattern to follow
|
||||
- `src/NT8.Core/Sizing/BasicPositionSizer.cs` - Pattern to follow
|
||||
- `src/NT8.Core/OMS/BasicOrderManager.cs` - Pattern to extend
|
||||
- `tests/NT8.Core.Tests/Risk/BasicRiskManagerTests.cs` - Test pattern
|
||||
|
||||
## Communication
|
||||
|
||||
When you need clarification:
|
||||
1. Check `OMS_Design_Specification.md` first
|
||||
2. Check existing code patterns in `src/NT8.Core/Risk/` or `src/NT8.Core/Sizing/`
|
||||
1. Check `Phase2_Implementation_Guide.md` first
|
||||
2. Check existing Phase 1 code patterns
|
||||
3. If still uncertain, ask before implementing
|
||||
|
||||
**Remember:** This is production trading code. When in doubt, ask rather than guess.
|
||||
|
||||
## Current Status
|
||||
|
||||
**Completed:**
|
||||
- ✅ Phase 0: Foundation
|
||||
- ✅ Phase 1: Basic OMS, Risk, Sizing (34 tests passing)
|
||||
|
||||
**In Progress:**
|
||||
- 🔄 Phase 2: Enhanced Risk & Sizing ← **YOU ARE HERE**
|
||||
|
||||
**Next:**
|
||||
- ⏭️ Phase 3: Market Microstructure
|
||||
- ⏭️ Phase 4: Intelligence & Grading
|
||||
- ⏭️ Phase 5: Analytics
|
||||
- ⏭️ Phase 6: Advanced Features
|
||||
|
||||
**Progress:** ~10% → ~20% (Phase 2 will double completed functionality)
|
||||
|
||||
Reference in New Issue
Block a user