Production hardening: kill switch, circuit breaker, trailing stops, log level, holiday calendar
Some checks failed
Build and Test / build (push) Has been cancelled

This commit is contained in:
2026-02-24 15:00:41 -05:00
parent 0e36fe5d23
commit a87152effb
50 changed files with 12849 additions and 752 deletions

View File

@@ -1,200 +1,96 @@
# Project Context - Phase 2
# Project Context — NT8 SDK (Production Hardening Phase)
You are working on the **NT8 SDK** - an institutional-grade trading SDK for NinjaTrader 8.
You are working on the **NT8 SDK** an institutional-grade algorithmic trading framework for NinjaTrader 8.
This is production trading software. Bugs cause real financial losses.
## Project Purpose
---
This is production trading software used for automated futures trading (ES, NQ, MES, MNQ, CL, GC). Code quality is critical because:
- Bugs can cause real financial losses
- System runs 24/5 during market hours
- Performance requirements are strict (<200ms latency)
- This is institutional-grade, not hobbyist code
## What Is Already Built (Do Not Touch)
## Current Phase: Phase 2 - Enhanced Risk & Sizing
All core trading logic is complete and has 240+ passing tests:
You are implementing **advanced risk management and intelligent position sizing**.
| Layer | Status | Key Files |
|---|---|---|
| Risk (Tier 1-3) | ✅ Complete | `src/NT8.Core/Risk/` |
| Position Sizing | ✅ Complete | `src/NT8.Core/Sizing/` |
| OMS / Order Lifecycle | ✅ Complete | `src/NT8.Core/OMS/` |
| Intelligence | ✅ Complete | `src/NT8.Core/Intelligence/` |
| Analytics | ✅ Complete | `src/NT8.Core/Analytics/` |
| Execution Utilities | ✅ Complete | `src/NT8.Core/Execution/` |
| Market Data | ✅ Complete | `src/NT8.Core/MarketData/` |
### 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)
**NT8 Order Execution is ALREADY WIRED.**
`NT8StrategyBase.SubmitOrderToNT8()` calls `EnterLong`, `EnterShort`, `SetStopLoss`, and
`SetProfitTarget` directly. The execution path works end-to-end. Do not re-implement it.
### 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
## What You Are Fixing (The Active Task List)
### CRITICAL — `NT8StrategyBase.cs`
**Gap 1 — No kill switch**
`NT8StrategyBase` has no `EnableKillSwitch` NinjaScript parameter and no early-exit in `OnBarUpdate()`.
A runaway strategy cannot be stopped without killing NinjaTrader.
**Fix:** Add `EnableKillSwitch` (bool NinjaScript property) and `EnableVerboseLogging` property.
Add kill switch check as the FIRST thing in `OnBarUpdate()`.
→ See `TASK-01-kill-switch.md`
**Gap 2 — `ExecutionCircuitBreaker` not wired**
`src/NT8.Core/Execution/ExecutionCircuitBreaker.cs` is complete and tested.
It is never instantiated. Orders submit regardless of latency or rejection conditions.
**Fix:** Instantiate in `InitializeSdkComponents()`, gate orders in `SubmitOrderToNT8()`, wire rejections in `OnOrderUpdate()`.
→ See `TASK-02-circuit-breaker.md`
### HIGH — `TrailingStopManager.cs`
**Gap 3 — Placeholder stop math returns zero**
`CalculateNewStopPrice()` FixedTrailing branch: `marketPrice - (x - x)` = always zero movement.
ATRTrailing and Chandelier also have meaningless placeholder formulas.
**Fix:** Replace with real calculations using `TrailingStopConfig.TrailingAmountTicks` and `AtrMultiplier`.
→ See `TASK-03-trailing-stop.md`
### HIGH — `BasicLogger.cs`
**Gap 4 — No log-level filter**
Every log statement writes to console unconditionally. Cannot suppress debug noise in production.
**Fix:** Add `MinimumLevel` property (defaults to `Information`). Suppress messages below threshold.
→ See `TASK-04-log-level.md`
### MEDIUM — `SessionManager.cs`
**Gap 5 — No holiday awareness**
`IsRegularTradingHours()` checks session times only. Will attempt to trade on Christmas, Thanksgiving, etc.
**Fix:** Add static CME holiday set for 2025/2026. Return `false` on those dates.
→ See `TASK-05-session-holidays.md`
---
## Architecture (Read Before Touching Anything)
```
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) - Phase 1 ✅ (enhancing in Phase 2)
↓ manages order lifecycle
NT8 Adapter Layer (INT8OrderAdapter) - Future
↓ bridges to NinjaTrader 8
NinjaTrader 8 Platform
SimpleORBStrategy.OnBar()
returns StrategyIntent
NT8StrategyBase.OnBarUpdate()
↓ [TASK-01: kill switch check here, first]
↓ calls ProcessStrategyIntent()
↓ calls _riskManager.ValidateOrder()
↓ calls _positionSizer.CalculateSize()
↓ calls SubmitOrderToNT8()
↓ [TASK-02: circuit breaker gate here]
↓ calls EnterLong/EnterShort/SetStopLoss/SetProfitTarget (already works)
NT8 callbacks → OnOrderUpdate / OnExecutionUpdate
↓ [TASK-02: record rejections in circuit breaker here]
```
## Your Current Task
Implement **Enhanced Risk & Sizing** with these deliverables:
### 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)
- Market microstructure (Phase 3)
- Advanced order types (Phase 3)
- Confluence scoring (Phase 4)
- ML-based features (Phase 6)
## Key Design Principles
### 1. Risk-First Architecture
ALL trading operations flow through risk management before execution.
The pattern is: Strategy Risk Sizing OMS NT8
**NEVER bypass risk checks.**
### 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 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
- 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
All calculations must be deterministic for:
- Backtesting accuracy
- Replay debugging
- Audit trails
---
## Technology Constraints
### Language & Framework
- C# 5.0 syntax ONLY (no C# 6+)
- .NET Framework 4.8 (not .NET Core/5+/6+)
- Target: Windows desktop environment
### Libraries
- Newtonsoft.Json (for serialization)
- Microsoft.Extensions.Logging (for logging)
- Microsoft.Extensions.DependencyInjection (for DI)
- System.Text.Json (not available)
- Any .NET Core/5+/6+ libraries
### Testing
- xUnit for test framework
- FluentAssertions for assertions
- Bogus for test data generation (if needed)
- Mock adapters for isolation
## Reference Documents
You have access to these design documents:
- `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 15 Phase 2 files created
- [ ] `verify-build.bat` passes
- [ ] >90 total tests passing
- [ ] >80% test coverage for new code
- [ ] No C# 6+ syntax
- [ ] Thread safety verified
- [ ] Performance targets met
- [ ] 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 `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)
- **C# 5.0 only** — no `$""`, no `?.`, no `=>` on methods/properties, no `nameof()`, no `out var`
- **.NET Framework 4.8** — not .NET Core/5+/6+
- **NinjaScript managed orders** — `EnterLong`, `EnterShort`, `SetStopLoss`, `SetProfitTarget`
- `string.Format()` everywhere, never string interpolation
- All `Dictionary`, `HashSet` access inside `lock (_lock)` blocks
- XML doc comments on all public members
- `try/catch` on all public methods with `LogError` in the catch