Sprint 3: Production Hardening — 9 tasks completed
## Summary Implemented 9 production-hardening tasks across risk, execution, calendar, and governance. All changes verified: build clean (0 errors), 492 tests passing (404 core + 78 integration + 10 perf). ## Core Changes ### Risk & Portfolio (3 tasks) - **GAP-019** Portfolio Heat Tier 3.5: Added MaxHeatPct (default 3%) to AdvancedRiskConfig; ValidatePortfolioHeat() computes TotalOpenRisk + NewTradeRisk / Equity * 100; rejects when exceeded. - **GAP-003** RiskPerTrade <= MaxTradeRisk Assertion: RiskPerTrade property in RiskConfig; throws ArgumentException at ValidateOrder() if RiskPerTrade > MaxTradeRisk; 3 unit tests. - **GAP-005** GetRiskStatus() Live Config: _currentDailyLossLimit field updated from config.DailyLossLimit on each ValidateOrder(); GetRiskStatus() returns actual value; 3 unit tests. ### Execution & Position Management (3 tasks) - **TASK-06a** Runner Mode Architecture: RunnerMode enum (Auto/Mode1DualLeg/Mode2RunnerOnly/ Mode3ScalerOnly/Disabled); ResolveRunnerMode() logic; 4-mode SubmitOrderToNT8() behavior. - **TASK-06b** ATR Dynamic Stop: EnableDynamicStop, AtrPeriod, AtrMultiplier, MinStopTicks, MaxStopTicks; computes dynStop = clamp(round(ATR/TickSize * Mult), Min, Max); overrides intent.StopTicks. - **GAP-006** Position-Close Re-arm: OnPositionUpdate() sends clear_trade_taken when flat; EnableBarBasedRearm parameter gates legacy bar-driven re-arm (default false for live). ### Strategy Intelligence (2 tasks) - **GAP-004** orbRangeTicks Fix: DailyBarContext.OrbRangeTicks field; computed from actual ORB high/low / TickSize; passed to Factor 7 (ORBvsATR). - **GAP-010** Short-Side Regime Filter: EnableShortTrendFilter param; vetoes shorts when AVWAP slope > 0 (bullish); configurable, default true. ### Calendar & Trailing (2 tasks) - **GAP-008** CME Holiday Awareness: NEW CmeHolidayCalendar.cs with 9 observed holidays + Good Friday (Easter calc); EnableCMEHolidayGuard skips ORB window on holidays. - **GAP-009** ATR Trailing Real ATR: EnableATRTrailing, ATRTrailingPeriod (14), ATRTrailingMultiplier (2.0), ATRTrailingMinTicks (8), ATRTrailingMaxTicks (60); computes trailTicks from ATR(Close,Period)[0]. ## Governance - SPRINT_BOARD.md, current_status.md, decisions.md (DEC-20260711-01 through -09), NEXT_PROMPT.md updated - All 9 tasks moved ACTIVE -> COMPLETED; GAP-011 (Gitea CI) now ACTIVE ## Verification - verify-build.bat: 0 errors, 0 warnings - Tests: 492 passing (404 core + 78 integration + 10 performance) ## Files - Modified: 13 source, 3 test, 9 governance - Deleted: 28 obsolete spec/docs - Added: 1 new module (NT8.Core.Calendar), governance files - Dual-deployed to NT8 Custom\Strategies\ ## Rollback Tag: sprint3-production-hardening-complete To revert: git reset --hard sprint3-production-hardening-complete
This commit is contained in:
192
docs/archive/ai-setup/AI_DEVELOPMENT_GUIDELINES.md
Normal file
192
docs/archive/ai-setup/AI_DEVELOPMENT_GUIDELINES.md
Normal file
@@ -0,0 +1,192 @@
|
||||
# NT8 SDK - AI Development Guidelines
|
||||
|
||||
## 🚨 CRITICAL: .NET Framework 4.8 Compatibility Requirements
|
||||
|
||||
This project MUST maintain compatibility with NinjaTrader 8, which requires:
|
||||
- **.NET Framework 4.8** (NOT .NET Core/.NET 5+)
|
||||
- **C# 5.0 language features only**
|
||||
- **Traditional class syntax** (NO records, nullable references, etc.)
|
||||
|
||||
## Language Restrictions (C# 5.0 Only)
|
||||
|
||||
### ❌ FORBIDDEN FEATURES
|
||||
- `record` types → Use `class` with constructors
|
||||
- Nullable reference types (`string?`) → Use `string`
|
||||
- String interpolation (`$"Hello {name}"`) → Use `String.Format("Hello {0}", name)`
|
||||
- Dictionary initializers (`new Dictionary<string, object> { ["key"] = value }`) → Use `dict.Add("key", value)`
|
||||
- Pattern matching → Use `switch` statements or `if/else`
|
||||
- Auto-property initializers → Initialize in constructor
|
||||
- Expression-bodied members → Use full method bodies
|
||||
- `nameof` operator → Use string literals
|
||||
- Exception filters → Use try/catch blocks
|
||||
- Async Main → Use traditional Main methods
|
||||
|
||||
### ✅ ALLOWED FEATURES
|
||||
- Traditional classes with properties and methods
|
||||
- Constructors with parameters
|
||||
- Standard interfaces and inheritance
|
||||
- LINQ (System.Linq)
|
||||
- Generics
|
||||
- Extension methods
|
||||
- Lambda expressions
|
||||
- Anonymous types
|
||||
- var keyword
|
||||
- Traditional async/await (with Task)
|
||||
|
||||
## Project Structure Rules
|
||||
|
||||
### Framework Targeting
|
||||
ALL projects must target `net48`:
|
||||
```xml
|
||||
<TargetFramework>net48</TargetFramework>
|
||||
<LangVersion>5.0</LangVersion>
|
||||
```
|
||||
|
||||
### Package Restrictions
|
||||
- **NO Microsoft.Extensions.*** packages (use custom implementations)
|
||||
- **NO System.Text.Json** (use Newtonsoft.Json)
|
||||
- **NO modern testing frameworks** (use MSTest for .NET Framework)
|
||||
|
||||
### Required Using Statements
|
||||
Always include these for basic functionality:
|
||||
```csharp
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks; // if async needed
|
||||
```
|
||||
|
||||
## Architecture Rules
|
||||
|
||||
### 1. Risk-First Design
|
||||
- ALL trading intents MUST pass through IRiskManager
|
||||
- Risk validation happens BEFORE position sizing
|
||||
- No strategy can bypass risk controls
|
||||
|
||||
### 2. Thin Strategy Pattern
|
||||
- Strategies implement ONLY signal generation
|
||||
- No direct market access from strategies
|
||||
- All execution goes through SDK framework
|
||||
|
||||
### 3. Deterministic Behavior
|
||||
- Same inputs MUST produce same outputs
|
||||
- No random number generation without seeds
|
||||
- All calculations must be reproducible
|
||||
|
||||
## Code Style Requirements
|
||||
|
||||
### Class Structure
|
||||
```csharp
|
||||
// ✅ Correct C# 5.0 class
|
||||
public class StrategyIntent
|
||||
{
|
||||
public string Symbol { get; set; }
|
||||
public OrderSide Side { get; set; }
|
||||
|
||||
public StrategyIntent(string symbol, OrderSide side)
|
||||
{
|
||||
Symbol = symbol;
|
||||
Side = side;
|
||||
}
|
||||
}
|
||||
|
||||
// ❌ FORBIDDEN - Record syntax
|
||||
public record StrategyIntent(string Symbol, OrderSide Side);
|
||||
```
|
||||
|
||||
### Dictionary Initialization
|
||||
```csharp
|
||||
// ✅ Correct C# 5.0 syntax
|
||||
var metrics = new Dictionary<string, object>();
|
||||
metrics.Add("trade_risk", riskAmount);
|
||||
metrics.Add("daily_pnl", dailyPnL);
|
||||
|
||||
// ❌ FORBIDDEN - Dictionary initializer
|
||||
var metrics = new Dictionary<string, object>
|
||||
{
|
||||
["trade_risk"] = riskAmount,
|
||||
["daily_pnl"] = dailyPnL
|
||||
};
|
||||
```
|
||||
|
||||
### String Formatting
|
||||
```csharp
|
||||
// ✅ Correct C# 5.0 syntax
|
||||
_logger.LogDebug("Order approved: {0} {1} risk=${2:F2}",
|
||||
intent.Symbol, intent.Side, tradeRisk);
|
||||
|
||||
// ❌ FORBIDDEN - String interpolation
|
||||
_logger.LogDebug($"Order approved: {intent.Symbol} {intent.Side} risk=${tradeRisk:F2}");
|
||||
```
|
||||
|
||||
## Testing Requirements
|
||||
|
||||
### Use MSTest Framework
|
||||
```csharp
|
||||
[TestClass]
|
||||
public class BasicRiskManagerTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void ValidateOrder_ShouldPass()
|
||||
{
|
||||
// Test implementation
|
||||
Assert.IsTrue(result.Allow);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Test Coverage Requirements
|
||||
- Minimum 80% code coverage for core components
|
||||
- All risk scenarios must be tested
|
||||
- All position sizing calculations must be validated
|
||||
|
||||
## Build Verification
|
||||
|
||||
Before committing ANY code, run:
|
||||
```bash
|
||||
.\verify-build.bat
|
||||
```
|
||||
|
||||
This MUST pass with zero errors and warnings.
|
||||
|
||||
## Phase Development Rules
|
||||
|
||||
### Phase 1 Focus Areas (ONLY)
|
||||
- NT8 adapter implementations
|
||||
- Market data integration
|
||||
- Order execution system
|
||||
- Enhanced risk controls (Tier 2)
|
||||
|
||||
### DO NOT IMPLEMENT
|
||||
- Advanced features from later phases
|
||||
- Modern C# language features
|
||||
- Complex UI components
|
||||
- Performance optimizations (until Phase 3)
|
||||
|
||||
## Common Pitfalls to Avoid
|
||||
|
||||
1. **Using modern C# syntax** - Stick to C# 5.0 only
|
||||
2. **Adding .NET Core packages** - Use .NET Framework compatible only
|
||||
3. **Bypassing risk management** - All trades must go through IRiskManager
|
||||
4. **Complex inheritance hierarchies** - Keep design simple and testable
|
||||
5. **Hardcoding values** - Use configuration classes
|
||||
|
||||
## AI Agent Checklist
|
||||
|
||||
Before implementing ANY feature:
|
||||
- [ ] Does this maintain .NET Framework 4.8 compatibility?
|
||||
- [ ] Does this use only C# 5.0 language features?
|
||||
- [ ] Does this follow the risk-first architecture?
|
||||
- [ ] Does this include appropriate error handling?
|
||||
- [ ] Does this include unit tests?
|
||||
- [ ] Does this compile without warnings?
|
||||
|
||||
## Emergency Contacts
|
||||
|
||||
If agents encounter compatibility issues:
|
||||
1. Check this document first
|
||||
2. Review existing working code patterns
|
||||
3. Test with `.\verify-build.bat`
|
||||
4. Flag for human review if unsure
|
||||
|
||||
Remember: **Compatibility with NT8 is non-negotiable.** When in doubt, use simpler, more traditional code patterns.
|
||||
314
docs/archive/ai-setup/AI_TEAM_SETUP_DOCUMENTATION.md
Normal file
314
docs/archive/ai-setup/AI_TEAM_SETUP_DOCUMENTATION.md
Normal file
@@ -0,0 +1,314 @@
|
||||
# NT8 SDK - AI Team Configuration and Setup Documentation
|
||||
|
||||
## Overview
|
||||
This document provides the complete setup and configuration guide for managing AI development teams working on the NT8 Institutional SDK. It covers the technical requirements, repository structure, and governance mechanisms established to ensure .NET Framework 4.8 compatibility and institutional-grade code quality.
|
||||
|
||||
## Project Background
|
||||
|
||||
### Business Context
|
||||
- **Objective**: Build institutional trading SDK for NinjaTrader 8 integration
|
||||
- **Architecture**: Risk-first design with thin strategy plugins
|
||||
- **Critical Requirement**: Must maintain .NET Framework 4.8 compatibility for NT8
|
||||
- **Quality Standard**: Zero-tolerance for compilation errors, institutional-grade risk management
|
||||
|
||||
### Technical Challenge Solved
|
||||
- **Problem**: AI team initially built with .NET Core 9 and modern C# features
|
||||
- **Impact**: Incompatible with NinjaTrader 8's .NET Framework 4.8 requirement
|
||||
- **Solution**: Complete framework conversion with comprehensive AI guardrails
|
||||
- **Result**: Working build with enforced compatibility standards
|
||||
|
||||
## Repository Structure and Location
|
||||
|
||||
### Repository Path
|
||||
```
|
||||
C:\dev\nt8-sdk\
|
||||
```
|
||||
|
||||
### Key Directory Structure
|
||||
```
|
||||
nt8-sdk/
|
||||
├── src/
|
||||
│ ├── NT8.Core/ # Core framework (risk, sizing, logging)
|
||||
│ ├── NT8.Adapters/ # NT8 integration layer
|
||||
│ ├── NT8.Strategies/ # Strategy implementations
|
||||
│ └── NT8.Contracts/ # Data transfer objects
|
||||
├── tests/
|
||||
│ ├── NT8.Core.Tests/ # Unit tests (MSTest)
|
||||
│ ├── NT8.Integration.Tests/ # Integration tests
|
||||
│ └── NT8.Performance.Tests/ # Performance tests
|
||||
├── docs/ # Documentation
|
||||
└── [AI Configuration Files] # See below
|
||||
```
|
||||
|
||||
## AI Team Configuration Files
|
||||
|
||||
### 1. Core Guidelines (MUST READ)
|
||||
| File | Purpose | Priority |
|
||||
|------|---------|----------|
|
||||
| `AI_DEVELOPMENT_GUIDELINES.md` | Core compatibility requirements, forbidden features | CRITICAL |
|
||||
| `CODE_STYLE_GUIDE.md` | Required C# 5.0 patterns and examples | CRITICAL |
|
||||
| `CODE_REVIEW_CHECKLIST.md` | Pre-commit verification checklist | CRITICAL |
|
||||
| `.aiconfig` | AI agent workflow and configuration | HIGH |
|
||||
|
||||
### 2. Build and Quality Control
|
||||
| File | Purpose | Usage |
|
||||
|------|---------|-------|
|
||||
| `verify-build.bat` | Complete build verification script | Run before every commit |
|
||||
| `.editorconfig` | Code formatting and style rules | Automatic enforcement |
|
||||
| `Directory.Build.props` | MSBuild configuration for all projects | Framework targeting |
|
||||
|
||||
### 3. Documentation
|
||||
| File | Purpose | Audience |
|
||||
|------|---------|----------|
|
||||
| `README.md` | Project overview and quick start | All developers |
|
||||
| `NET_FRAMEWORK_CONVERSION.md` | Background on compatibility changes | Context for decisions |
|
||||
| `CODE_REVIEW_CHECKLIST.md` | Quality assurance process | Reviewers and AI agents |
|
||||
|
||||
## Critical Technical Requirements
|
||||
|
||||
### Framework and Language Constraints
|
||||
```xml
|
||||
<!-- ALL projects must use this configuration -->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net48</TargetFramework>
|
||||
<LangVersion>5.0</LangVersion>
|
||||
<Nullable>disable</Nullable>
|
||||
</PropertyGroup>
|
||||
```
|
||||
|
||||
### Forbidden Technologies and Features
|
||||
#### Language Features (C# 6+ - Will Not Compile)
|
||||
- ❌ `record` types → Use `class` with constructors
|
||||
- ❌ Nullable reference types (`string?`) → Use `string`
|
||||
- ❌ String interpolation (`$"..."`) → Use `String.Format()`
|
||||
- ❌ Dictionary initializers (`new Dict { ["key"] = value }`) → Use `.Add()`
|
||||
- ❌ Pattern matching → Use `switch` or `if/else`
|
||||
- ❌ Auto-property initializers → Initialize in constructor
|
||||
|
||||
#### Package Dependencies
|
||||
- ❌ Microsoft.Extensions.* packages → Use custom implementations
|
||||
- ❌ System.Text.Json → Use Newtonsoft.Json
|
||||
- ❌ xUnit/NUnit → Use MSTest only
|
||||
- ❌ .NET Core packages → Use .NET Framework compatible only
|
||||
|
||||
### Required Patterns (C# 5.0 Compatible)
|
||||
|
||||
#### Class Definition
|
||||
```csharp
|
||||
public class ClassName
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public string PropertyName { get; set; }
|
||||
|
||||
public ClassName(ILogger logger, string property)
|
||||
{
|
||||
if (logger == null) throw new ArgumentNullException("logger");
|
||||
_logger = logger;
|
||||
PropertyName = property;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Dictionary Initialization
|
||||
```csharp
|
||||
// ✅ Correct C# 5.0 syntax
|
||||
var metrics = new Dictionary<string, object>();
|
||||
metrics.Add("trade_risk", riskAmount);
|
||||
metrics.Add("daily_pnl", dailyPnL);
|
||||
```
|
||||
|
||||
#### String Formatting
|
||||
```csharp
|
||||
// ✅ Correct C# 5.0 syntax
|
||||
_logger.LogDebug("Order approved: {0} {1} risk=${2:F2}",
|
||||
intent.Symbol, intent.Side, tradeRisk);
|
||||
```
|
||||
|
||||
## Development Workflow for AI Teams
|
||||
|
||||
### Pre-Development Setup
|
||||
1. **Repository Access**: Ensure team has access to `C:\dev\nt8-sdk`
|
||||
2. **Baseline Verification**: Run `.\verify-build.bat` - must pass
|
||||
3. **Documentation Review**: Team must read all CRITICAL priority files
|
||||
4. **Pattern Familiarization**: Review existing code in `src/NT8.Core/`
|
||||
|
||||
### Development Process
|
||||
#### Before Starting Any Task
|
||||
```bash
|
||||
# 1. Verify baseline build
|
||||
cd C:\dev\nt8-sdk
|
||||
.\verify-build.bat
|
||||
|
||||
# 2. Review guidelines for the specific module
|
||||
# 3. Check existing patterns in relevant source files
|
||||
```
|
||||
|
||||
#### During Development
|
||||
- Follow patterns in `CODE_STYLE_GUIDE.md` exactly
|
||||
- Use only C# 5.0 compatible syntax
|
||||
- Maintain risk-first architecture (all trades through IRiskManager)
|
||||
- Add unit tests for new functionality using MSTest
|
||||
|
||||
#### Before Committing
|
||||
```bash
|
||||
# MANDATORY verification
|
||||
.\verify-build.bat
|
||||
```
|
||||
Must output: `✅ All checks passed!`
|
||||
|
||||
### Quality Gates (Zero Tolerance)
|
||||
Every commit must pass ALL of these:
|
||||
1. ✅ Compilation with zero errors
|
||||
2. ✅ Zero build warnings
|
||||
3. ✅ All tests passing
|
||||
4. ✅ C# 5.0 syntax compliance
|
||||
5. ✅ Architecture compliance (risk-first)
|
||||
6. ✅ Code style compliance
|
||||
|
||||
## Architecture Governance
|
||||
|
||||
### Risk-First Design (Non-Negotiable)
|
||||
All trading logic must follow this pattern:
|
||||
```csharp
|
||||
// 1. Strategy generates intent
|
||||
var intent = strategy.OnBar(bar, context);
|
||||
|
||||
// 2. Risk validation (MANDATORY)
|
||||
var riskDecision = riskManager.ValidateOrder(intent, context, config);
|
||||
if (!riskDecision.Allow)
|
||||
{
|
||||
// Trade rejected - log and stop
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Position sizing
|
||||
var sizingResult = positionSizer.CalculateSize(intent, context, config);
|
||||
|
||||
// 4. Order execution (Phase 1)
|
||||
// Will be implemented in NT8 adapters
|
||||
```
|
||||
|
||||
### Thin Strategy Pattern
|
||||
Strategies must only:
|
||||
- Generate trading signals (`StrategyIntent`)
|
||||
- Implement `IStrategy` interface
|
||||
- NOT access markets directly
|
||||
- NOT implement risk management
|
||||
- NOT handle position sizing
|
||||
|
||||
## Phase Management
|
||||
|
||||
### Current Phase: Phase 1
|
||||
**Focus Areas (ONLY implement these):**
|
||||
- NT8 adapter implementations
|
||||
- Market data provider integration
|
||||
- Order management system
|
||||
- Enhanced risk controls (Tier 2 only)
|
||||
|
||||
**DO NOT Implement:**
|
||||
- Features from Phases 2-6
|
||||
- UI components
|
||||
- Advanced analytics
|
||||
- Performance optimizations (until Phase 3)
|
||||
- Confluence scoring (Phase 4)
|
||||
|
||||
### Phase Boundaries
|
||||
Each phase has specific deliverables and constraints. AI teams must stay within current phase scope to avoid architecture drift and maintain project timeline.
|
||||
|
||||
## Error Prevention and Troubleshooting
|
||||
|
||||
### Common Build Failures
|
||||
| Error Type | Cause | Solution |
|
||||
|------------|-------|----------|
|
||||
| CS8026: Feature not available in C# 5 | Used modern C# syntax | Check `CODE_STYLE_GUIDE.md` for correct pattern |
|
||||
| CS0246: Type not found | Used incompatible package | Use .NET Framework compatible alternatives |
|
||||
| Build warnings | Various style issues | Review `.editorconfig` and existing patterns |
|
||||
|
||||
### Verification Script Failures
|
||||
If `.\verify-build.bat` fails:
|
||||
1. Read error messages carefully
|
||||
2. Check against `CODE_REVIEW_CHECKLIST.md`
|
||||
3. Review recent changes for C# 6+ features
|
||||
4. Compare against working code patterns
|
||||
|
||||
### Architecture Violations
|
||||
Common violations and fixes:
|
||||
- **Direct market access**: Route through SDK framework
|
||||
- **Risk bypass**: Ensure all trades go through IRiskManager
|
||||
- **Complex inheritance**: Use composition and interfaces
|
||||
- **Framework incompatibility**: Use only .NET Framework 4.8 features
|
||||
|
||||
## Team Management Guidelines
|
||||
|
||||
### Onboarding New AI Agents
|
||||
1. **Documentation Review**: Complete read of all CRITICAL files
|
||||
2. **Pattern Training**: Review existing implementations in `src/NT8.Core/`
|
||||
3. **Verification Practice**: Run build script multiple times
|
||||
4. **Test Implementation**: Create simple test class following MSTest patterns
|
||||
|
||||
### Code Review Process
|
||||
#### For Human Reviewers
|
||||
1. Run `.\verify-build.bat` first
|
||||
2. Use `CODE_REVIEW_CHECKLIST.md` systematically
|
||||
3. Verify phase compliance (no future features)
|
||||
4. Check architecture compliance (risk-first)
|
||||
|
||||
#### For AI Agents (Self-Review)
|
||||
1. Complete `CODE_REVIEW_CHECKLIST.md` before submission
|
||||
2. Verify against `AI_DEVELOPMENT_GUIDELINES.md`
|
||||
3. Confirm build verification passes
|
||||
4. Review code against existing patterns
|
||||
|
||||
### Performance Monitoring
|
||||
Track these metrics for AI team effectiveness:
|
||||
- **Build Success Rate**: Should be >95% after onboarding
|
||||
- **Compliance Rate**: C# 5.0 syntax violations should be <5%
|
||||
- **Architecture Adherence**: Risk-first pattern compliance should be 100%
|
||||
- **Phase Boundary Respect**: Zero implementations of future phase features
|
||||
|
||||
## Maintenance and Updates
|
||||
|
||||
### Regular Maintenance Tasks
|
||||
- **Weekly**: Run `.\verify-build.bat` on clean checkout
|
||||
- **Monthly**: Review AI team compliance metrics
|
||||
- **Per Phase**: Update phase-specific guidelines as needed
|
||||
|
||||
### Updating AI Guidelines
|
||||
When making changes to AI configuration:
|
||||
1. Update relevant documentation files
|
||||
2. Test with AI team on non-critical changes
|
||||
3. Verify build compatibility
|
||||
4. Communicate changes clearly
|
||||
|
||||
### Backup and Recovery
|
||||
- Repository should be backed up regularly
|
||||
- All configuration files are version controlled
|
||||
- Build verification script provides quick health check
|
||||
|
||||
## Success Metrics
|
||||
|
||||
### Technical Metrics
|
||||
- **Build Success Rate**: >98%
|
||||
- **Compilation Time**: <30 seconds for full solution
|
||||
- **Test Pass Rate**: 100%
|
||||
- **Warning Count**: 0
|
||||
|
||||
### Quality Metrics
|
||||
- **Code Coverage**: >80% for core components
|
||||
- **Architecture Compliance**: 100% (all trades through risk management)
|
||||
- **Framework Compatibility**: 100% (.NET Framework 4.8)
|
||||
- **Phase Compliance**: 100% (no future features implemented)
|
||||
|
||||
## Conclusion
|
||||
|
||||
This configuration provides comprehensive governance for AI development teams working on the NT8 SDK. The combination of technical constraints, clear guidelines, automated verification, and human oversight ensures high-quality, compatible code that meets institutional trading requirements.
|
||||
|
||||
The setup balances AI team autonomy with necessary constraints, providing clear patterns to follow while preventing common compatibility pitfalls. Regular verification and monitoring ensure ongoing compliance with critical requirements.
|
||||
|
||||
---
|
||||
|
||||
**Document Version**: 1.0
|
||||
**Last Updated**: Current implementation
|
||||
**Next Review**: After Phase 1 completion
|
||||
**Owner**: NT8 SDK Project Team
|
||||
261
docs/archive/ai-setup/ai_agent_tasks.md
Normal file
261
docs/archive/ai-setup/ai_agent_tasks.md
Normal file
@@ -0,0 +1,261 @@
|
||||
# AI Agent Task Breakdown for NT8 Integration
|
||||
|
||||
## Current Execution Status (Updated 2026-02-16)
|
||||
|
||||
- [x] Task 1: Base NT8 Strategy Wrapper completed
|
||||
- [x] Task 2: NT8 Data Conversion Layer completed
|
||||
- [x] Task 3: Simple ORB NT8 Wrapper completed
|
||||
- [x] Task 4: NT8 Order Execution Adapter completed
|
||||
- [x] Task 5: NT8 Logging Adapter completed
|
||||
- [x] Task 6: Deployment System completed
|
||||
- [x] Task 7: Integration Tests completed
|
||||
|
||||
### Recent Validation Snapshot
|
||||
|
||||
- [x] [`verify-build.bat`](verify-build.bat) passing
|
||||
- [x] Integration tests passing
|
||||
- [x] Core tests passing
|
||||
- [x] Performance tests passing
|
||||
|
||||
## Phase 1A Tasks (Priority Order)
|
||||
|
||||
### Task 1: Create Base NT8 Strategy Wrapper ⭐ CRITICAL
|
||||
**Objective**: Create foundation wrapper that all NT8 strategies will inherit from
|
||||
|
||||
**Deliverables**:
|
||||
- `src/NT8.Adapters/Wrappers/BaseNT8StrategyWrapper.cs`
|
||||
- Inherits from NinjaTrader's `Strategy` class
|
||||
- Provides common SDK integration functionality
|
||||
- Handles data conversion and error handling
|
||||
|
||||
**Requirements**:
|
||||
- MUST compile in NT8 NinjaScript Editor
|
||||
- MUST use C# 5.0 syntax only
|
||||
- MUST include proper NT8 attributes and lifecycle methods
|
||||
- MUST integrate with existing SDK Core components
|
||||
|
||||
**Success Criteria**:
|
||||
- [ ] Compiles without errors in NT8
|
||||
- [ ] Base functionality works (can create derived strategies)
|
||||
- [ ] Proper error handling and logging
|
||||
- [ ] Follows established code patterns
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Create NT8 Data Conversion Layer ⭐ CRITICAL
|
||||
**Objective**: Convert between NT8 data formats and SDK data models
|
||||
|
||||
**Deliverables**:
|
||||
- `src/NT8.Adapters/NinjaTrader/NT8DataConverter.cs`
|
||||
- Methods to convert bars, account info, positions
|
||||
- Proper error handling for invalid data
|
||||
|
||||
**Key Methods Needed**:
|
||||
```csharp
|
||||
public static BarData ConvertBar(/* NT8 bar data */)
|
||||
public static StrategyContext ConvertContext(/* NT8 context */)
|
||||
public static AccountInfo ConvertAccount(/* NT8 account */)
|
||||
public static Position ConvertPosition(/* NT8 position */)
|
||||
```
|
||||
|
||||
**Success Criteria**:
|
||||
- [ ] All conversions preserve data integrity
|
||||
- [ ] Handles edge cases (null data, invalid values)
|
||||
- [ ] Performance acceptable (<1ms per conversion)
|
||||
- [ ] Comprehensive unit tests
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Create Simple ORB NT8 Wrapper ⭐ HIGH
|
||||
**Objective**: Create working example of NT8 strategy using SDK
|
||||
|
||||
**Deliverables**:
|
||||
- `src/NT8.Adapters/Wrappers/SimpleORBNT8Wrapper.cs`
|
||||
- Complete NT8 strategy that uses SDK Simple ORB strategy
|
||||
- User-friendly parameter UI
|
||||
- Integration with risk management and position sizing
|
||||
|
||||
**Required Parameters (NT8 UI)**:
|
||||
- Stop Loss Ticks
|
||||
- Profit Target Ticks
|
||||
- ORB Period Minutes
|
||||
- Daily Loss Limit
|
||||
- Risk Per Trade
|
||||
- Position Sizing Method
|
||||
|
||||
**Success Criteria**:
|
||||
- [ ] Shows up in NT8 strategy list
|
||||
- [ ] Parameters display correctly in NT8 UI
|
||||
- [ ] Strategy executes trades on simulation account
|
||||
- [ ] Risk controls work as expected
|
||||
- [ ] Position sizing calculates correctly
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Create NT8 Order Execution Adapter ⭐ HIGH
|
||||
**Objective**: Handle order submission and management through NT8
|
||||
|
||||
**Deliverables**:
|
||||
- `src/NT8.Adapters/NinjaTrader/NT8OrderAdapter.cs`
|
||||
- Convert SDK StrategyIntent to NT8 orders
|
||||
- Handle order status updates and fills
|
||||
- Integrate with NT8's order management
|
||||
|
||||
**Key Functionality**:
|
||||
- Submit market/limit orders
|
||||
- Set stop loss and profit targets
|
||||
- Handle partial fills
|
||||
- Order cancellation
|
||||
- Position flattening
|
||||
|
||||
**Success Criteria**:
|
||||
- [ ] Orders execute correctly in NT8
|
||||
- [ ] Stop loss and targets set properly
|
||||
- [ ] Order status updates flow back to SDK
|
||||
- [ ] Emergency flatten works
|
||||
- [ ] Proper error handling for rejected orders
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Create NT8 Logging Adapter 🔶 MEDIUM
|
||||
**Objective**: Bridge SDK logging with NT8's output systems
|
||||
|
||||
**Deliverables**:
|
||||
- `src/NT8.Adapters/NinjaTrader/NT8LoggingAdapter.cs`
|
||||
- Route SDK log messages to NT8 Output window
|
||||
- Maintain correlation IDs and structured logging
|
||||
- Performance optimized (non-blocking)
|
||||
|
||||
**Success Criteria**:
|
||||
- [ ] SDK log messages appear in NT8 Output window
|
||||
- [ ] Log levels properly mapped
|
||||
- [ ] No performance impact on trading
|
||||
- [ ] Structured data preserved where possible
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Create Deployment System 🔶 MEDIUM
|
||||
**Objective**: Streamline deployment of SDK components to NT8
|
||||
|
||||
**Deliverables**:
|
||||
- `deployment/deploy-to-nt8.bat` script
|
||||
- `deployment/NT8/install-instructions.md`
|
||||
- Copy SDK DLLs to NT8 directories
|
||||
- Copy strategy wrappers to NT8 custom folder
|
||||
|
||||
**Automation**:
|
||||
```bash
|
||||
# Copy DLLs
|
||||
copy src\NT8.Core\bin\Release\net48\*.dll "Documents\NinjaTrader 8\bin\Custom\"
|
||||
|
||||
# Copy strategies
|
||||
copy src\NT8.Adapters\Wrappers\*.cs "Documents\NinjaTrader 8\bin\Custom\Strategies\"
|
||||
```
|
||||
|
||||
**Success Criteria**:
|
||||
- [ ] One-click deployment to NT8
|
||||
- [ ] Proper file permissions and locations
|
||||
- [ ] Verification that deployment succeeded
|
||||
- [ ] Rollback capability
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Create Integration Tests 🔶 MEDIUM
|
||||
**Objective**: Comprehensive testing of NT8 integration
|
||||
|
||||
**Deliverables**:
|
||||
- `tests/NT8.Integration.Tests/NT8WrapperTests.cs`
|
||||
- Test data conversion accuracy
|
||||
- Test order execution flow
|
||||
- Test parameter mapping
|
||||
|
||||
**Test Scenarios**:
|
||||
- Happy path: Strategy generates trade, executes successfully
|
||||
- Risk rejection: Trade rejected by risk management
|
||||
- Invalid data: Handle corrupt/missing NT8 data
|
||||
- Configuration: Parameter changes take effect
|
||||
|
||||
**Success Criteria**:
|
||||
- [ ] All integration scenarios tested
|
||||
- [ ] Tests can run without full NT8 installation
|
||||
- [ ] Mock NT8 components for CI/CD
|
||||
- [ ] Performance benchmarks included
|
||||
|
||||
## Implementation Guidelines for AI Agents
|
||||
|
||||
### Before Starting Any Task:
|
||||
1. **Read Requirements**: Review `NT8_INTEGRATION_GUIDELINES.md`
|
||||
2. **Check Dependencies**: Ensure previous tasks are complete
|
||||
3. **Verify Build**: Run `.\verify-build.bat` to confirm baseline
|
||||
4. **Study NT8 Docs**: Understand NT8 APIs being used
|
||||
|
||||
### During Implementation:
|
||||
1. **Follow Patterns**: Use existing SDK code patterns
|
||||
2. **Test Early**: Compile in NT8 frequently during development
|
||||
3. **Handle Errors**: Robust error handling for all NT8 interactions
|
||||
4. **Document Code**: Clear comments for NT8-specific code
|
||||
|
||||
### Before Submitting:
|
||||
1. **Compile Check**: MUST compile in NT8 NinjaScript Editor
|
||||
2. **Unit Tests**: Add tests for all new functionality
|
||||
3. **Integration Test**: Test with actual NT8 if possible
|
||||
4. **Code Review**: Use `CODE_REVIEW_CHECKLIST.md`
|
||||
|
||||
## Task Dependencies
|
||||
|
||||
```
|
||||
Task 1 (Base Wrapper) → Must complete first
|
||||
↓
|
||||
Task 2 (Data Conversion) → Required for Task 3
|
||||
↓
|
||||
Task 3 (ORB Wrapper) ← Depends on Task 1 & 2
|
||||
↓
|
||||
Task 4 (Order Adapter) ← Can start after Task 2
|
||||
↓
|
||||
Task 5 (Logging) ← Independent, can start anytime
|
||||
↓
|
||||
Task 6 (Deployment) ← Needs Tasks 1-4 complete
|
||||
↓
|
||||
Task 7 (Integration Tests) ← Needs all other tasks
|
||||
```
|
||||
|
||||
## Quality Gates for Each Task
|
||||
|
||||
### Compilation Gate
|
||||
- [ ] Compiles in main SDK build (`.\verify-build.bat`)
|
||||
- [ ] Compiles in NT8 NinjaScript Editor (for wrapper classes)
|
||||
- [ ] Zero warnings in both environments
|
||||
|
||||
### Functionality Gate
|
||||
- [ ] Core functionality works as designed
|
||||
- [ ] Error handling covers expected failure cases
|
||||
- [ ] Performance meets requirements
|
||||
- [ ] Integration with existing SDK components
|
||||
|
||||
### Testing Gate
|
||||
- [ ] Unit tests for all new classes/methods
|
||||
- [ ] Integration tests for NT8 interaction
|
||||
- [ ] Manual testing on NT8 simulation account
|
||||
- [ ] Documentation updated
|
||||
|
||||
### Code Quality Gate
|
||||
- [ ] Follows C# 5.0 syntax requirements
|
||||
- [ ] Matches established code patterns
|
||||
- [ ] Proper error handling and logging
|
||||
- [ ] Clear, maintainable code structure
|
||||
|
||||
## Risk Mitigation
|
||||
|
||||
### Technical Risks
|
||||
- **NT8 API Changes**: Test with multiple NT8 versions if possible
|
||||
- **Performance Issues**: Profile integration points early
|
||||
- **Memory Leaks**: Proper disposal of NT8 objects
|
||||
- **Threading Issues**: NT8 strategies run on UI thread
|
||||
|
||||
### Integration Risks
|
||||
- **SDK Compatibility**: Ensure no breaking changes to Core
|
||||
- **Configuration Conflicts**: Handle parameter validation gracefully
|
||||
- **Order Execution**: Thorough testing of trade execution paths
|
||||
- **Error Propagation**: Ensure SDK errors surface properly in NT8
|
||||
|
||||
This task breakdown provides clear, actionable work items for AI agents while maintaining the quality and compatibility standards established for the NT8 SDK project.
|
||||
258
docs/archive/ai-setup/ai_success_metrics.md
Normal file
258
docs/archive/ai-setup/ai_success_metrics.md
Normal file
@@ -0,0 +1,258 @@
|
||||
# AI Team Success Metrics and Monitoring
|
||||
|
||||
## Key Performance Indicators (KPIs)
|
||||
|
||||
### Technical Quality Metrics
|
||||
|
||||
#### Build Success Rate
|
||||
**Target**: >98%
|
||||
- **Measurement**: Percentage of commits that pass `.\verify-build.bat`
|
||||
- **Tracking**: Daily monitoring of build failures
|
||||
- **Action Threshold**: <95% triggers immediate review
|
||||
|
||||
#### NT8 Compilation Success
|
||||
**Target**: 100% for wrapper classes
|
||||
- **Measurement**: Wrapper classes compile successfully in NT8 NinjaScript Editor
|
||||
- **Tracking**: Test compilation with each wrapper submission
|
||||
- **Action Threshold**: Any compilation failure requires immediate fix
|
||||
|
||||
#### Code Quality Score
|
||||
**Target**: >90%
|
||||
- **Measurement**: Automated analysis of:
|
||||
- C# 5.0 syntax compliance
|
||||
- Proper error handling patterns
|
||||
- Code documentation coverage
|
||||
- Adherence to established patterns
|
||||
- **Tracking**: Weekly quality audits
|
||||
- **Action Threshold**: <85% triggers code review and training
|
||||
|
||||
### Functional Metrics
|
||||
|
||||
#### Test Coverage
|
||||
**Target**: >80% for new code
|
||||
- **Measurement**: Unit test coverage percentage
|
||||
- **Tracking**: Coverage reports with each task completion
|
||||
- **Action Threshold**: <75% requires additional tests before approval
|
||||
|
||||
#### Integration Success Rate
|
||||
**Target**: 100%
|
||||
- **Measurement**: NT8 integration tests pass on first attempt
|
||||
- **Tracking**: Integration test results for each wrapper
|
||||
- **Action Threshold**: Any failure requires root cause analysis
|
||||
|
||||
#### Performance Compliance
|
||||
**Target**: <200ms latency for critical paths
|
||||
- **Measurement**: Execution time for data conversion and order processing
|
||||
- **Tracking**: Performance benchmarks with each release
|
||||
- **Action Threshold**: >300ms triggers optimization review
|
||||
|
||||
### Architecture Compliance
|
||||
|
||||
#### Risk-First Pattern Adherence
|
||||
**Target**: 100%
|
||||
- **Measurement**: All trading paths go through IRiskManager
|
||||
- **Tracking**: Code review verification
|
||||
- **Action Threshold**: Any bypass attempt requires immediate correction
|
||||
|
||||
#### Framework Compatibility
|
||||
**Target**: 100%
|
||||
- **Measurement**: All code uses .NET Framework 4.8 compatible features
|
||||
- **Tracking**: Compilation and runtime testing
|
||||
- **Action Threshold**: Any incompatibility requires immediate fix
|
||||
|
||||
#### Phase Boundary Respect
|
||||
**Target**: 100%
|
||||
- **Measurement**: No implementation of future phase features
|
||||
- **Tracking**: Feature scope review with each task
|
||||
- **Action Threshold**: Any scope creep requires task redefinition
|
||||
|
||||
## Monitoring Dashboard
|
||||
|
||||
### Daily Metrics (Automated)
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ NT8 SDK - Daily AI Team Metrics │
|
||||
├─────────────────────────────────────────┤
|
||||
│ Build Success Rate: 98.2% ✅ │
|
||||
│ NT8 Compilation: 100.0% ✅ │
|
||||
│ Test Coverage: 87.3% ✅ │
|
||||
│ Performance Compliance: 100.0% ✅ │
|
||||
│ │
|
||||
│ Tasks Completed Today: 3 │
|
||||
│ Code Quality Issues: 1 │
|
||||
│ Integration Failures: 0 │
|
||||
│ │
|
||||
│ 🚨 Alerts: None │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Weekly Report Template
|
||||
```markdown
|
||||
# NT8 SDK AI Team - Weekly Report
|
||||
|
||||
## Summary
|
||||
- **Tasks Completed**: X/Y planned
|
||||
- **Quality Score**: X% (Target: >90%)
|
||||
- **Build Success**: X% (Target: >98%)
|
||||
- **Integration Success**: X% (Target: 100%)
|
||||
|
||||
## Achievements
|
||||
- [List major completions]
|
||||
- [Notable quality improvements]
|
||||
- [Performance optimizations]
|
||||
|
||||
## Issues and Resolutions
|
||||
- [Technical challenges encountered]
|
||||
- [Solutions implemented]
|
||||
- [Process improvements made]
|
||||
|
||||
## Next Week Focus
|
||||
- [Priority tasks]
|
||||
- [Risk mitigation items]
|
||||
- [Quality improvements planned]
|
||||
|
||||
## Metrics Trends
|
||||
- [Graphs/charts of key metrics]
|
||||
- [Improvement/degradation analysis]
|
||||
- [Corrective actions needed]
|
||||
```
|
||||
|
||||
## Quality Assurance Process
|
||||
|
||||
### Code Review Checklist Integration
|
||||
Every submission must pass:
|
||||
|
||||
#### Automated Checks (Pre-Review)
|
||||
- [ ] `.\verify-build.bat` passes
|
||||
- [ ] NT8 compilation test passes (for wrappers)
|
||||
- [ ] Unit tests achieve >80% coverage
|
||||
- [ ] No C# 6+ syntax detected
|
||||
- [ ] No .NET Core dependencies detected
|
||||
|
||||
#### Human Review (Post-Automated)
|
||||
- [ ] Follows established code patterns
|
||||
- [ ] Proper error handling implemented
|
||||
- [ ] Integration points correctly implemented
|
||||
- [ ] Documentation adequate
|
||||
- [ ] Performance acceptable
|
||||
|
||||
### Escalation Matrix
|
||||
|
||||
#### Green Zone (Normal Operations)
|
||||
- Build success >98%
|
||||
- Quality score >90%
|
||||
- All tests passing
|
||||
- **Action**: Continue normal operations
|
||||
|
||||
#### Yellow Zone (Caution)
|
||||
- Build success 95-98%
|
||||
- Quality score 85-90%
|
||||
- <5% test failures
|
||||
- **Action**: Daily quality review, additional training
|
||||
|
||||
#### Red Zone (Immediate Action Required)
|
||||
- Build success <95%
|
||||
- Quality score <85%
|
||||
- >5% test failures
|
||||
- **Action**: Stop new development, focus on fixing issues
|
||||
|
||||
## Training and Improvement
|
||||
|
||||
### Onboarding Metrics for New AI Agents
|
||||
|
||||
#### Week 1 Targets
|
||||
- [ ] Complete documentation review (100%)
|
||||
- [ ] Pass initial code pattern quiz (>90%)
|
||||
- [ ] Submit first simple task (compiles successfully)
|
||||
- [ ] Demonstrate NT8 compilation process
|
||||
|
||||
#### Week 2 Targets
|
||||
- [ ] Complete medium complexity task
|
||||
- [ ] Achieve >85% code quality score
|
||||
- [ ] Pass integration testing
|
||||
- [ ] Demonstrate error handling patterns
|
||||
|
||||
#### Week 4 Targets (Full Productivity)
|
||||
- [ ] Achieve target metrics consistently
|
||||
- [ ] Complete complex tasks independently
|
||||
- [ ] Mentor newer AI agents
|
||||
- [ ] Contribute to process improvements
|
||||
|
||||
### Continuous Improvement Process
|
||||
|
||||
#### Monthly Review Process
|
||||
1. **Metrics Analysis**: Review all KPIs and trends
|
||||
2. **Root Cause Analysis**: Identify systemic issues
|
||||
3. **Process Updates**: Refine guidelines and templates
|
||||
4. **Training Updates**: Address knowledge gaps
|
||||
5. **Tool Improvements**: Enhance automation and validation
|
||||
|
||||
#### Feedback Loops
|
||||
- **Daily**: Automated metric collection and alerts
|
||||
- **Weekly**: Team performance review and planning
|
||||
- **Monthly**: Process and guideline improvements
|
||||
- **Quarterly**: Strategic direction and goal adjustment
|
||||
|
||||
## Risk Management
|
||||
|
||||
### Technical Risk Monitoring
|
||||
|
||||
#### High-Risk Indicators
|
||||
- Multiple build failures in sequence
|
||||
- NT8 compilation issues appearing
|
||||
- Performance degradation trends
|
||||
- Increasing error rates in integration tests
|
||||
|
||||
#### Mitigation Strategies
|
||||
- **Immediate**: Halt new development, focus on fixes
|
||||
- **Short-term**: Additional code reviews and pair programming
|
||||
- **Long-term**: Enhanced training and better tooling
|
||||
|
||||
### Project Risk Monitoring
|
||||
|
||||
#### Schedule Risk Indicators
|
||||
- Tasks consistently missing deadlines
|
||||
- Quality requiring extensive rework
|
||||
- Integration issues blocking progress
|
||||
|
||||
#### Quality Risk Indicators
|
||||
- Declining code quality scores
|
||||
- Increasing technical debt
|
||||
- Pattern violations becoming common
|
||||
|
||||
## Success Celebration and Recognition
|
||||
|
||||
### Achievement Milestones
|
||||
- **First Successful NT8 Integration**: Complete wrapper compiles and runs
|
||||
- **Quality Excellence**: Sustained >95% quality scores
|
||||
- **Performance Achievement**: All performance targets met
|
||||
- **Zero Defect Delivery**: Full task with no post-delivery issues
|
||||
|
||||
### Recognition Criteria
|
||||
- Exceptional code quality
|
||||
- Innovation in solving complex problems
|
||||
- Helping other agents improve
|
||||
- Identifying and fixing systemic issues
|
||||
|
||||
## Reporting and Communication
|
||||
|
||||
### Stakeholder Updates
|
||||
|
||||
#### Daily (Automated)
|
||||
- Build status dashboard
|
||||
- Critical issue alerts
|
||||
- Progress against milestones
|
||||
|
||||
#### Weekly (Manual)
|
||||
- Detailed progress report
|
||||
- Quality metrics analysis
|
||||
- Risk assessment update
|
||||
- Next week planning
|
||||
|
||||
#### Monthly (Strategic)
|
||||
- Overall project health
|
||||
- Trend analysis and forecasting
|
||||
- Process improvement recommendations
|
||||
- Resource and timeline adjustments
|
||||
|
||||
This comprehensive monitoring system ensures AI team success while maintaining the high standards required for institutional trading software.
|
||||
101
docs/archive/completed-tasks/TASK-01-kill-switch.md
Normal file
101
docs/archive/completed-tasks/TASK-01-kill-switch.md
Normal file
@@ -0,0 +1,101 @@
|
||||
# TASK-01: Add Kill Switch + Verbose Logging Toggle
|
||||
|
||||
**File:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`
|
||||
**Priority:** CRITICAL
|
||||
**Estimated time:** 45 min
|
||||
**No dependencies**
|
||||
|
||||
---
|
||||
|
||||
## Exact Changes Required
|
||||
|
||||
### 1. Add two new NinjaScript properties to the `#region User-Configurable Properties` block
|
||||
|
||||
Add these after the existing `MaxContracts` property:
|
||||
|
||||
```csharp
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Kill Switch (Flatten + Stop)", GroupName = "Emergency Controls", Order = 1)]
|
||||
public bool EnableKillSwitch { get; set; }
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Verbose Logging", GroupName = "Debug", Order = 1)]
|
||||
public bool EnableVerboseLogging { get; set; }
|
||||
```
|
||||
|
||||
### 2. Add a private field near the other private fields at the top of the class
|
||||
|
||||
```csharp
|
||||
private bool _killSwitchTriggered;
|
||||
```
|
||||
|
||||
### 3. Set defaults in `OnStateChange` → `State.SetDefaults` block, after the existing defaults
|
||||
|
||||
```csharp
|
||||
EnableKillSwitch = false;
|
||||
EnableVerboseLogging = false;
|
||||
_killSwitchTriggered = false;
|
||||
```
|
||||
|
||||
### 4. Add kill switch check at the TOP of `OnBarUpdate()`, before EVERYTHING else
|
||||
|
||||
The very first lines of `OnBarUpdate()` must become:
|
||||
|
||||
```csharp
|
||||
protected override void OnBarUpdate()
|
||||
{
|
||||
// Kill switch check — must be first
|
||||
if (EnableKillSwitch)
|
||||
{
|
||||
if (!_killSwitchTriggered)
|
||||
{
|
||||
_killSwitchTriggered = true;
|
||||
Print(string.Format("[SDK] KILL SWITCH ACTIVATED at {0} — flattening all positions.", Time[0]));
|
||||
try
|
||||
{
|
||||
ExitLong("KillSwitch");
|
||||
ExitShort("KillSwitch");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Print(string.Format("[SDK] Kill switch flatten error: {0}", ex.Message));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Existing guards follow unchanged
|
||||
if (!_sdkInitialized || _sdkStrategy == null)
|
||||
{ ... }
|
||||
...
|
||||
```
|
||||
|
||||
### 5. Add verbose logging to `ProcessStrategyIntent()` — wrap existing Print calls
|
||||
|
||||
Replace the existing bare `Print(...)` calls in `ProcessStrategyIntent()` with guarded versions:
|
||||
|
||||
```csharp
|
||||
// Change every Print(...) inside ProcessStrategyIntent() to:
|
||||
if (EnableVerboseLogging)
|
||||
Print(string.Format("...existing message..."));
|
||||
```
|
||||
|
||||
The `Print` call that shows the intent being generated in `OnBarUpdate` (not in `ProcessStrategyIntent`) should remain unguarded — that one is important.
|
||||
|
||||
---
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `EnableKillSwitch` visible in NT8 strategy parameter dialog under "Emergency Controls"
|
||||
- [ ] `EnableVerboseLogging` visible under "Debug"
|
||||
- [ ] Setting `EnableKillSwitch = true` mid-run causes `ExitLong("KillSwitch")` and `ExitShort("KillSwitch")` on next bar
|
||||
- [ ] After kill switch triggers, every subsequent bar returns immediately (no strategy logic runs)
|
||||
- [ ] `verify-build.bat` passes with zero errors
|
||||
|
||||
---
|
||||
|
||||
## Do NOT Change
|
||||
|
||||
- Constructor or `InitializeSdkComponents()`
|
||||
- `SubmitOrderToNT8()`
|
||||
- Any OMS, Risk, Sizing, or Strategy logic
|
||||
140
docs/archive/completed-tasks/TASK-02-circuit-breaker.md
Normal file
140
docs/archive/completed-tasks/TASK-02-circuit-breaker.md
Normal file
@@ -0,0 +1,140 @@
|
||||
# TASK-02: Wire ExecutionCircuitBreaker into NT8StrategyBase
|
||||
|
||||
**File:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`
|
||||
**Priority:** CRITICAL
|
||||
**Depends on:** TASK-01 must be done first (file already open/modified)
|
||||
**Estimated time:** 45 min
|
||||
|
||||
---
|
||||
|
||||
## Background
|
||||
|
||||
`ExecutionCircuitBreaker` at `src/NT8.Core/Execution/ExecutionCircuitBreaker.cs` is complete and tested.
|
||||
Its public API is:
|
||||
- `bool ShouldAllowOrder()` — returns false when circuit is Open
|
||||
- `void OnSuccess()` — call after a successful order submission
|
||||
- `void OnFailure()` — call after a failed order submission
|
||||
- `void RecordOrderRejection(string reason)` — call when NT8 rejects an order
|
||||
- `void Reset()` — resets to Closed state
|
||||
|
||||
The `ExecutionCircuitBreaker` constructor:
|
||||
```csharp
|
||||
public ExecutionCircuitBreaker(
|
||||
ILogger<ExecutionCircuitBreaker> logger,
|
||||
int failureThreshold = 3,
|
||||
TimeSpan? timeout = null,
|
||||
TimeSpan? retryTimeout = null,
|
||||
int latencyWindowSize = 100,
|
||||
int rejectionWindowSize = 10)
|
||||
```
|
||||
|
||||
**Problem:** It is never instantiated. `NT8StrategyBase` submits orders with no circuit breaker gate.
|
||||
|
||||
---
|
||||
|
||||
## Exact Changes Required
|
||||
|
||||
### 1. Add using statement at top of `NT8StrategyBase.cs`
|
||||
|
||||
```csharp
|
||||
using NT8.Core.Execution;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
```
|
||||
|
||||
### 2. Add private field alongside the other private fields
|
||||
|
||||
```csharp
|
||||
private ExecutionCircuitBreaker _circuitBreaker;
|
||||
```
|
||||
|
||||
### 3. Initialize in `InitializeSdkComponents()`, after `_positionSizer = new BasicPositionSizer(_logger);`
|
||||
|
||||
```csharp
|
||||
_circuitBreaker = new ExecutionCircuitBreaker(
|
||||
NullLogger<ExecutionCircuitBreaker>.Instance,
|
||||
failureThreshold: 3,
|
||||
timeout: TimeSpan.FromSeconds(30));
|
||||
```
|
||||
|
||||
### 4. Gate `SubmitOrderToNT8()` — add check at top of the method
|
||||
|
||||
```csharp
|
||||
private void SubmitOrderToNT8(OmsOrderRequest request, StrategyIntent intent)
|
||||
{
|
||||
// Circuit breaker gate
|
||||
if (_circuitBreaker != null && !_circuitBreaker.ShouldAllowOrder())
|
||||
{
|
||||
var state = _circuitBreaker.GetState();
|
||||
Print(string.Format("[SDK] Circuit breaker OPEN — order blocked: {0}", state.Reason));
|
||||
if (_logger != null)
|
||||
_logger.LogWarning("Circuit breaker blocked order: {0}", state.Reason);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// ... EXISTING submit logic unchanged ...
|
||||
var orderName = string.Format("SDK_{0}_{1}", intent.Symbol, DateTime.Now.Ticks);
|
||||
_executionAdapter.SubmitOrder(request, orderName);
|
||||
|
||||
if (request.Side == OmsOrderSide.Buy)
|
||||
{ ... existing EnterLong/EnterLongLimit/etc ... }
|
||||
else if (request.Side == OmsOrderSide.Sell)
|
||||
{ ... existing EnterShort/etc ... }
|
||||
|
||||
if (intent.StopTicks > 0)
|
||||
SetStopLoss(orderName, CalculationMode.Ticks, (int)intent.StopTicks, false);
|
||||
|
||||
if (intent.TargetTicks.HasValue && intent.TargetTicks.Value > 0)
|
||||
SetProfitTarget(orderName, CalculationMode.Ticks, (int)intent.TargetTicks.Value);
|
||||
|
||||
// Mark success after submission
|
||||
if (_circuitBreaker != null)
|
||||
_circuitBreaker.OnSuccess();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_circuitBreaker != null)
|
||||
_circuitBreaker.OnFailure();
|
||||
|
||||
Print(string.Format("[SDK] SubmitOrderToNT8 failed: {0}", ex.Message));
|
||||
if (_logger != null)
|
||||
_logger.LogError("SubmitOrderToNT8 failed: {0}", ex.Message);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Wire rejections in `OnOrderUpdate()`
|
||||
|
||||
In the existing `OnOrderUpdate()` override, after the null/name checks, add:
|
||||
|
||||
```csharp
|
||||
// Record NT8 rejections in circuit breaker
|
||||
if (orderState == NinjaTrader.Cbi.OrderState.Rejected && _circuitBreaker != null)
|
||||
{
|
||||
var reason = string.Format("{0} {1}", errorCode, nativeError ?? string.Empty);
|
||||
_circuitBreaker.RecordOrderRejection(reason);
|
||||
Print(string.Format("[SDK] Order rejected by NT8: {0}", reason));
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `ExecutionCircuitBreaker` is instantiated in `InitializeSdkComponents()`
|
||||
- [ ] `SubmitOrderToNT8()` checks `ShouldAllowOrder()` before submitting — if false, prints message and returns
|
||||
- [ ] `OnOrderUpdate()` calls `RecordOrderRejection()` when `orderState == OrderState.Rejected`
|
||||
- [ ] `OnSuccess()` called after successful order submission
|
||||
- [ ] `OnFailure()` called in catch block
|
||||
- [ ] `verify-build.bat` passes with zero errors
|
||||
- [ ] Existing 240+ tests still pass: `dotnet test NT8-SDK.sln --verbosity minimal`
|
||||
|
||||
---
|
||||
|
||||
## Do NOT Change
|
||||
|
||||
- `ExecutionCircuitBreaker.cs` — already correct, just use it
|
||||
- Any Core layer files
|
||||
- Any test files
|
||||
151
docs/archive/completed-tasks/TASK-03-trailing-stop.md
Normal file
151
docs/archive/completed-tasks/TASK-03-trailing-stop.md
Normal file
@@ -0,0 +1,151 @@
|
||||
# TASK-03: Fix TrailingStopManager Placeholder Math
|
||||
|
||||
**File:** `src/NT8.Core/Execution/TrailingStopManager.cs`
|
||||
**Priority:** HIGH
|
||||
**No dependencies**
|
||||
**Estimated time:** 1 hour
|
||||
|
||||
---
|
||||
|
||||
## Background
|
||||
|
||||
`CalculateNewStopPrice()` has three broken cases:
|
||||
|
||||
**FixedTrailing (broken):**
|
||||
```csharp
|
||||
return marketPrice - (position.AverageFillPrice - position.AverageFillPrice); // always 0
|
||||
```
|
||||
|
||||
**ATRTrailing (placeholder):**
|
||||
```csharp
|
||||
return marketPrice - (position.AverageFillPrice * 0.01m); // uses fill price as ATR proxy
|
||||
```
|
||||
|
||||
**Chandelier (placeholder):**
|
||||
```csharp
|
||||
return marketPrice - (position.AverageFillPrice * 0.01m); // same placeholder
|
||||
```
|
||||
|
||||
The `TrailingStopConfig` class has these fields available — use them:
|
||||
- `TrailingAmountTicks` — integer, tick count for fixed trailing distance
|
||||
- `AtrMultiplier` — decimal, multiplier for ATR-based methods
|
||||
- `Type` — `StopType` enum
|
||||
|
||||
Look at `TrailingStopConfig` in the same file or nearby to confirm field names before editing.
|
||||
|
||||
---
|
||||
|
||||
## Exact Changes Required
|
||||
|
||||
Replace the entire `switch` body inside `CalculateNewStopPrice()` with correct math.
|
||||
|
||||
**Use tick size = `0.25m` as the default** (ES/NQ standard). The config should ideally carry tick size, but since it currently does not, use `0.25m` as the constant for now with a comment explaining it.
|
||||
|
||||
```csharp
|
||||
switch (type)
|
||||
{
|
||||
case StopType.FixedTrailing:
|
||||
{
|
||||
// Trail by a fixed number of ticks from current market price.
|
||||
// TrailingAmountTicks comes from config; default 8 if zero.
|
||||
var tickSize = 0.25m;
|
||||
var trailingTicks = config.TrailingAmountTicks > 0 ? config.TrailingAmountTicks : 8;
|
||||
var distance = trailingTicks * tickSize;
|
||||
|
||||
return position.Side == OMS.OrderSide.Buy
|
||||
? marketPrice - distance
|
||||
: marketPrice + distance;
|
||||
}
|
||||
|
||||
case StopType.ATRTrailing:
|
||||
{
|
||||
// Trail by AtrMultiplier * estimated ATR.
|
||||
// We do not have live ATR here, so approximate ATR as (EntryPrice * 0.005)
|
||||
// which is ~0.5% — a conservative proxy for ES/NQ.
|
||||
// TODO: pass actual ATR value via config when available.
|
||||
var atrMultiplier = config.AtrMultiplier > 0 ? config.AtrMultiplier : 2.0m;
|
||||
var estimatedAtr = position.AverageFillPrice * 0.005m;
|
||||
var distance = atrMultiplier * estimatedAtr;
|
||||
|
||||
return position.Side == OMS.OrderSide.Buy
|
||||
? marketPrice - distance
|
||||
: marketPrice + distance;
|
||||
}
|
||||
|
||||
case StopType.Chandelier:
|
||||
{
|
||||
// Chandelier exit: trail from highest high (approximated as marketPrice)
|
||||
// minus AtrMultiplier * ATR.
|
||||
// Full implementation requires bar history; use same ATR proxy for now.
|
||||
// TODO: pass highest-high and actual ATR via config.
|
||||
var chanMultiplier = config.AtrMultiplier > 0 ? config.AtrMultiplier : 3.0m;
|
||||
var estimatedAtr = position.AverageFillPrice * 0.005m;
|
||||
var distance = chanMultiplier * estimatedAtr;
|
||||
|
||||
return position.Side == OMS.OrderSide.Buy
|
||||
? marketPrice - distance
|
||||
: marketPrice + distance;
|
||||
}
|
||||
|
||||
case StopType.PercentageTrailing:
|
||||
{
|
||||
// Existing logic is correct — percentage of current price.
|
||||
var pctTrail = 0.02m;
|
||||
return position.Side == OMS.OrderSide.Buy
|
||||
? marketPrice * (1 - pctTrail)
|
||||
: marketPrice * (1 + pctTrail);
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
// Fixed trailing as fallback
|
||||
var tickSize = 0.25m;
|
||||
var ticks = config.TrailingAmountTicks > 0 ? config.TrailingAmountTicks : 8;
|
||||
return position.Side == OMS.OrderSide.Buy
|
||||
? marketPrice - (ticks * tickSize)
|
||||
: marketPrice + (ticks * tickSize);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**IMPORTANT:** The `config` variable is NOT currently a parameter to `CalculateNewStopPrice()`. The current signature is:
|
||||
```csharp
|
||||
public decimal CalculateNewStopPrice(StopType type, OMS.OrderStatus position, decimal marketPrice)
|
||||
```
|
||||
|
||||
You need to add `config` as a parameter:
|
||||
```csharp
|
||||
public decimal CalculateNewStopPrice(StopType type, OMS.OrderStatus position, decimal marketPrice, TrailingStopConfig config)
|
||||
```
|
||||
|
||||
Then fix the ONE call site inside `UpdateTrailingStop()`:
|
||||
```csharp
|
||||
var newStopPrice = CalculateNewStopPrice(trailingStop.Config.Type, trailingStop.Position, currentPrice, trailingStop.Config);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Also Create: New Unit Tests
|
||||
|
||||
Create `tests/NT8.Core.Tests/Execution/TrailingStopManagerFixedTests.cs`
|
||||
|
||||
```csharp
|
||||
// Tests that verify FixedTrailing actually moves the stop
|
||||
// Test 1: Long position, FixedTrailing 8 ticks → stop = marketPrice - (8 * 0.25) = marketPrice - 2.0
|
||||
// Test 2: Short position, FixedTrailing 8 ticks → stop = marketPrice + 2.0
|
||||
// Test 3: ATRTrailing multiplier 2 → stop distance > 0
|
||||
// Test 4: Stop only updates when favorable (existing UpdateTrailingStop logic test)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `FixedTrailing` for a long position at price 5100 with 8 ticks returns `5100 - 2.0 = 5098.0`
|
||||
- [ ] `FixedTrailing` for a short position at price 5100 with 8 ticks returns `5100 + 2.0 = 5102.0`
|
||||
- [ ] `ATRTrailing` returns a value meaningfully below market price for longs (not zero, not equal to price)
|
||||
- [ ] `Chandelier` returns a value meaningfully below market price for longs (not zero)
|
||||
- [ ] `CalculateNewStopPrice` signature updated — call site in `UpdateTrailingStop()` updated
|
||||
- [ ] New unit tests pass
|
||||
- [ ] All existing tests still pass
|
||||
- [ ] `verify-build.bat` passes
|
||||
116
docs/archive/completed-tasks/TASK-04-log-level.md
Normal file
116
docs/archive/completed-tasks/TASK-04-log-level.md
Normal file
@@ -0,0 +1,116 @@
|
||||
# TASK-04: Add Log Level Filter to BasicLogger
|
||||
|
||||
**File:** `src/NT8.Core/Logging/BasicLogger.cs`
|
||||
**Priority:** HIGH
|
||||
**No dependencies**
|
||||
**Estimated time:** 20 min
|
||||
|
||||
---
|
||||
|
||||
## Background
|
||||
|
||||
`BasicLogger` currently writes every log level to console unconditionally. When `EnableVerboseLogging` is false in NT8, you want to suppress `Debug` and `Trace` output.
|
||||
|
||||
The current `ILogger` interface (check `src/NT8.Core/Logging/ILogger.cs`) only defines:
|
||||
- `LogDebug`, `LogInformation`, `LogWarning`, `LogError`, `LogCritical`
|
||||
|
||||
---
|
||||
|
||||
## Exact Changes Required
|
||||
|
||||
### 1. Add `LogLevel` enum (check if it already exists first — search the project for `LogLevel`)
|
||||
|
||||
If it does NOT already exist, add it inside `BasicLogger.cs` or as a separate file in the same folder:
|
||||
|
||||
```csharp
|
||||
namespace NT8.Core.Logging
|
||||
{
|
||||
/// <summary>
|
||||
/// Log severity levels.
|
||||
/// </summary>
|
||||
public enum LogLevel
|
||||
{
|
||||
Debug = 0,
|
||||
Information = 1,
|
||||
Warning = 2,
|
||||
Error = 3,
|
||||
Critical = 4
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Add `MinimumLevel` property to `BasicLogger`
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Minimum log level to write. Messages below this level are suppressed.
|
||||
/// Default is Information.
|
||||
/// </summary>
|
||||
public LogLevel MinimumLevel { get; set; }
|
||||
```
|
||||
|
||||
### 3. Update constructor to default to `Information`
|
||||
|
||||
```csharp
|
||||
public BasicLogger(string categoryName = "")
|
||||
{
|
||||
_categoryName = categoryName;
|
||||
MinimumLevel = LogLevel.Information;
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Update `WriteLog()` to skip below minimum
|
||||
|
||||
Add a level parameter and check at the start:
|
||||
|
||||
```csharp
|
||||
private void WriteLog(LogLevel level, string levelLabel, string message, params object[] args)
|
||||
{
|
||||
if (level < MinimumLevel)
|
||||
return;
|
||||
|
||||
var timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff");
|
||||
var formattedMessage = args.Length > 0 ? String.Format(message, args) : message;
|
||||
var category = !String.IsNullOrEmpty(_categoryName) ? String.Format("[{0}] ", _categoryName) : "";
|
||||
Console.WriteLine(String.Format("{0} [{1}] {2}{3}", timestamp, levelLabel, category, formattedMessage));
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Update each public method to pass its level
|
||||
|
||||
```csharp
|
||||
public void LogDebug(string message, params object[] args)
|
||||
{
|
||||
WriteLog(LogLevel.Debug, "DEBUG", message, args);
|
||||
}
|
||||
|
||||
public void LogInformation(string message, params object[] args)
|
||||
{
|
||||
WriteLog(LogLevel.Information, "INFO", message, args);
|
||||
}
|
||||
|
||||
public void LogWarning(string message, params object[] args)
|
||||
{
|
||||
WriteLog(LogLevel.Warning, "WARN", message, args);
|
||||
}
|
||||
|
||||
public void LogError(string message, params object[] args)
|
||||
{
|
||||
WriteLog(LogLevel.Error, "ERROR", message, args);
|
||||
}
|
||||
|
||||
public void LogCritical(string message, params object[] args)
|
||||
{
|
||||
WriteLog(LogLevel.Critical, "CRITICAL", message, args);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `MinimumLevel = LogLevel.Warning` suppresses `LogDebug` and `LogInformation` calls
|
||||
- [ ] `LogWarning`, `LogError`, `LogCritical` still write when `MinimumLevel = LogLevel.Warning`
|
||||
- [ ] Default `MinimumLevel` is `Information` (backward compatible)
|
||||
- [ ] `verify-build.bat` passes
|
||||
- [ ] All existing tests pass (no test should be checking console output for Debug messages)
|
||||
105
docs/archive/completed-tasks/TASK-05-session-holidays.md
Normal file
105
docs/archive/completed-tasks/TASK-05-session-holidays.md
Normal file
@@ -0,0 +1,105 @@
|
||||
# TASK-05: Add CME Holiday Awareness to SessionManager
|
||||
|
||||
**File:** `src/NT8.Core/MarketData/SessionManager.cs`
|
||||
**Priority:** MEDIUM
|
||||
**No dependencies**
|
||||
**Estimated time:** 30 min
|
||||
|
||||
---
|
||||
|
||||
## Background
|
||||
|
||||
`IsRegularTradingHours()` currently only checks session time windows. It has no awareness of CME holidays, so the system would attempt to trade on Christmas, Thanksgiving, etc. when markets are closed.
|
||||
|
||||
---
|
||||
|
||||
## Exact Changes Required
|
||||
|
||||
### 1. Add a static holiday set as a private field on `SessionManager`
|
||||
|
||||
Add this inside the class (near the other private fields):
|
||||
|
||||
```csharp
|
||||
// CME US Futures holidays — markets closed all day on these dates.
|
||||
// Update annually. Dates are in the format new DateTime(year, month, day).
|
||||
private static readonly System.Collections.Generic.HashSet<DateTime> _cmeHolidays =
|
||||
new System.Collections.Generic.HashSet<DateTime>
|
||||
{
|
||||
// 2025 holidays
|
||||
new DateTime(2025, 1, 1), // New Year's Day
|
||||
new DateTime(2025, 1, 20), // Martin Luther King Jr. Day
|
||||
new DateTime(2025, 2, 17), // Presidents' Day
|
||||
new DateTime(2025, 4, 18), // Good Friday
|
||||
new DateTime(2025, 5, 26), // Memorial Day
|
||||
new DateTime(2025, 6, 19), // Juneteenth
|
||||
new DateTime(2025, 7, 4), // Independence Day
|
||||
new DateTime(2025, 9, 1), // Labor Day
|
||||
new DateTime(2025, 11, 27), // Thanksgiving
|
||||
new DateTime(2025, 12, 25), // Christmas Day
|
||||
|
||||
// 2026 holidays
|
||||
new DateTime(2026, 1, 1), // New Year's Day
|
||||
new DateTime(2026, 1, 19), // Martin Luther King Jr. Day
|
||||
new DateTime(2026, 2, 16), // Presidents' Day
|
||||
new DateTime(2026, 4, 3), // Good Friday
|
||||
new DateTime(2026, 5, 25), // Memorial Day
|
||||
new DateTime(2026, 6, 19), // Juneteenth
|
||||
new DateTime(2026, 7, 4), // Independence Day (observed Mon 7/3 if falls on Sat — keep both just in case)
|
||||
new DateTime(2026, 9, 7), // Labor Day
|
||||
new DateTime(2026, 11, 26), // Thanksgiving
|
||||
new DateTime(2026, 12, 25), // Christmas Day
|
||||
};
|
||||
```
|
||||
|
||||
### 2. Add a helper method
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Returns true if the given UTC date is a CME holiday (market closed all day).
|
||||
/// </summary>
|
||||
private static bool IsCmeHoliday(DateTime utcTime)
|
||||
{
|
||||
// Convert to ET for holiday date comparison
|
||||
try
|
||||
{
|
||||
var estTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime,
|
||||
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
|
||||
return _cmeHolidays.Contains(estTime.Date);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Update `IsRegularTradingHours()` to check holidays first
|
||||
|
||||
The existing method body is:
|
||||
```csharp
|
||||
var sessionInfo = GetCurrentSession(symbol, time);
|
||||
return sessionInfo.IsRegularHours;
|
||||
```
|
||||
|
||||
Replace with:
|
||||
```csharp
|
||||
// Markets are fully closed on CME holidays
|
||||
if (IsCmeHoliday(time))
|
||||
{
|
||||
_logger.LogInformation("Holiday detected for {0} on {1} — market closed.", symbol, time.Date);
|
||||
return false;
|
||||
}
|
||||
|
||||
var sessionInfo = GetCurrentSession(symbol, time);
|
||||
return sessionInfo.IsRegularHours;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `IsRegularTradingHours("ES", new DateTime(2025, 12, 25, 14, 0, 0, DateTimeKind.Utc))` returns `false`
|
||||
- [ ] `IsRegularTradingHours("ES", new DateTime(2025, 12, 26, 14, 0, 0, DateTimeKind.Utc))` returns `true` (normal day)
|
||||
- [ ] `IsRegularTradingHours("ES", new DateTime(2025, 11, 27, 14, 0, 0, DateTimeKind.Utc))` returns `false` (Thanksgiving)
|
||||
- [ ] `verify-build.bat` passes
|
||||
- [ ] All existing tests pass
|
||||
178
docs/archive/completed-tasks/TASK_01_WIRE_NT8_EXECUTION.md
Normal file
178
docs/archive/completed-tasks/TASK_01_WIRE_NT8_EXECUTION.md
Normal file
@@ -0,0 +1,178 @@
|
||||
# Task 1 — Wire NT8OrderAdapter.ExecuteInNT8()
|
||||
|
||||
**Priority:** CRITICAL
|
||||
**Estimated time:** 3–4 hours
|
||||
**Blocks:** All backtest and live trading
|
||||
**Status:** TODO
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
`NT8OrderAdapter.ExecuteInNT8()` in `src/NT8.Adapters/NinjaTrader/NT8OrderAdapter.cs` is a stub.
|
||||
It only logs to an internal list. The actual NT8 calls (`EnterLong`, `EnterShort`, `SetStopLoss`, `SetProfitTarget`) are in a commented-out block and never execute. This is why backtests show zero trades.
|
||||
|
||||
---
|
||||
|
||||
## What Needs to Change
|
||||
|
||||
### File: `src/NT8.Adapters/NinjaTrader/NT8OrderAdapter.cs`
|
||||
|
||||
The adapter currently has no reference to the actual NinjaScript `Strategy` object. It needs a way to call NT8 managed order methods. The pattern used by `NT8StrategyBase` is the right model to follow.
|
||||
|
||||
**Option A (Recommended):** Inject a callback delegate so the adapter can call NT8 methods without directly holding a NinjaScript reference.
|
||||
|
||||
Add a new `INT8ExecutionBridge` interface:
|
||||
```csharp
|
||||
// new file: src/NT8.Adapters/NinjaTrader/INT8ExecutionBridge.cs
|
||||
namespace NT8.Adapters.NinjaTrader
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides NT8OrderAdapter access to NinjaScript execution methods.
|
||||
/// Implemented by NT8StrategyBase.
|
||||
/// </summary>
|
||||
public interface INT8ExecutionBridge
|
||||
{
|
||||
/// <summary>Submit a long entry with stop and target.</summary>
|
||||
void EnterLongManaged(int quantity, string signalName, int stopTicks, int targetTicks, double tickSize);
|
||||
|
||||
/// <summary>Submit a short entry with stop and target.</summary>
|
||||
void EnterShortManaged(int quantity, string signalName, int stopTicks, int targetTicks, double tickSize);
|
||||
|
||||
/// <summary>Exit all long positions.</summary>
|
||||
void ExitLongManaged(string signalName);
|
||||
|
||||
/// <summary>Exit all short positions.</summary>
|
||||
void ExitShortManaged(string signalName);
|
||||
|
||||
/// <summary>Flatten the full position immediately.</summary>
|
||||
void FlattenAll();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Update `NT8OrderAdapter` constructor to accept `INT8ExecutionBridge`:
|
||||
```csharp
|
||||
public NT8OrderAdapter(INT8ExecutionBridge bridge)
|
||||
{
|
||||
if (bridge == null)
|
||||
throw new ArgumentNullException("bridge");
|
||||
_bridge = bridge;
|
||||
_executionHistory = new List<NT8OrderExecutionRecord>();
|
||||
}
|
||||
```
|
||||
|
||||
Implement `ExecuteInNT8()`:
|
||||
```csharp
|
||||
private void ExecuteInNT8(StrategyIntent intent, SizingResult sizing)
|
||||
{
|
||||
if (intent == null)
|
||||
throw new ArgumentNullException("intent");
|
||||
if (sizing == null)
|
||||
throw new ArgumentNullException("sizing");
|
||||
|
||||
var signalName = string.Format("SDK_{0}_{1}", intent.Symbol, intent.Side);
|
||||
|
||||
if (intent.Side == Common.Models.OrderSide.Buy)
|
||||
{
|
||||
_bridge.EnterLongManaged(
|
||||
sizing.Contracts,
|
||||
signalName,
|
||||
intent.StopTicks,
|
||||
intent.TargetTicks.HasValue ? intent.TargetTicks.Value : 0,
|
||||
intent.TickSize);
|
||||
}
|
||||
else if (intent.Side == Common.Models.OrderSide.Sell)
|
||||
{
|
||||
_bridge.EnterShortManaged(
|
||||
sizing.Contracts,
|
||||
signalName,
|
||||
intent.StopTicks,
|
||||
intent.TargetTicks.HasValue ? intent.TargetTicks.Value : 0,
|
||||
intent.TickSize);
|
||||
}
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
_executionHistory.Add(new NT8OrderExecutionRecord(
|
||||
intent.Symbol,
|
||||
intent.Side,
|
||||
intent.EntryType,
|
||||
sizing.Contracts,
|
||||
intent.StopTicks,
|
||||
intent.TargetTicks,
|
||||
DateTime.UtcNow));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### File: `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`
|
||||
|
||||
Implement `INT8ExecutionBridge` on `NT8StrategyBase`:
|
||||
```csharp
|
||||
public class NT8StrategyBase : Strategy, INT8ExecutionBridge
|
||||
{
|
||||
public void EnterLongManaged(int quantity, string signalName, int stopTicks, int targetTicks, double tickSize)
|
||||
{
|
||||
SetStopLoss(signalName, CalculationMode.Ticks, stopTicks, false);
|
||||
if (targetTicks > 0)
|
||||
SetProfitTarget(signalName, CalculationMode.Ticks, targetTicks);
|
||||
EnterLong(quantity, signalName);
|
||||
}
|
||||
|
||||
public void EnterShortManaged(int quantity, string signalName, int stopTicks, int targetTicks, double tickSize)
|
||||
{
|
||||
SetStopLoss(signalName, CalculationMode.Ticks, stopTicks, false);
|
||||
if (targetTicks > 0)
|
||||
SetProfitTarget(signalName, CalculationMode.Ticks, targetTicks);
|
||||
EnterShort(quantity, signalName);
|
||||
}
|
||||
|
||||
public void ExitLongManaged(string signalName)
|
||||
{
|
||||
ExitLong(signalName);
|
||||
}
|
||||
|
||||
public void ExitShortManaged(string signalName)
|
||||
{
|
||||
ExitShort(signalName);
|
||||
}
|
||||
|
||||
// FlattenAll already called in NT8 as: this.Account.Flatten(Instrument)
|
||||
// or: ExitLong(); ExitShort();
|
||||
public void FlattenAll()
|
||||
{
|
||||
ExitLong("EmergencyFlatten");
|
||||
ExitShort("EmergencyFlatten");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `NT8OrderAdapter` takes `INT8ExecutionBridge` in its constructor
|
||||
- [ ] `ExecuteInNT8()` calls the bridge (no more commented-out code)
|
||||
- [ ] `NT8StrategyBase` implements `INT8ExecutionBridge`
|
||||
- [ ] `OnOrderUpdate()` callback in `NT8OrderAdapter` updates `BasicOrderManager` state (pass the fill back)
|
||||
- [ ] `verify-build.bat` passes
|
||||
- [ ] A backtest run on SimpleORBNT8 produces actual trades (not zero)
|
||||
|
||||
---
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action |
|
||||
|---|---|
|
||||
| `src/NT8.Adapters/NinjaTrader/INT8ExecutionBridge.cs` | CREATE |
|
||||
| `src/NT8.Adapters/NinjaTrader/NT8OrderAdapter.cs` | MODIFY — implement `ExecuteInNT8()`, update constructor |
|
||||
| `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` | MODIFY — implement `INT8ExecutionBridge` |
|
||||
|
||||
---
|
||||
|
||||
## Do NOT Change
|
||||
|
||||
- `src/NT8.Core/OMS/BasicOrderManager.cs` — the OMS is correct
|
||||
- `src/NT8.Strategies/Examples/SimpleORBStrategy.cs` — strategy logic is correct
|
||||
- Any existing test files
|
||||
110
docs/archive/completed-tasks/TASK_02_EMERGENCY_KILL_SWITCH.md
Normal file
110
docs/archive/completed-tasks/TASK_02_EMERGENCY_KILL_SWITCH.md
Normal file
@@ -0,0 +1,110 @@
|
||||
# Task 2 — Emergency Kill Switch
|
||||
|
||||
**Priority:** CRITICAL
|
||||
**Estimated time:** 1.5–2 hours
|
||||
**Depends on:** Task 1 (INT8ExecutionBridge.FlattenAll must exist)
|
||||
**Status:** TODO
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
There is no way to stop a running strategy and flatten positions from the NinjaTrader UI without killing the entire application.
|
||||
`BasicOrderManager.FlattenAll()` exists in the SDK core but nothing surfaces it as a controllable NT8 strategy parameter.
|
||||
|
||||
---
|
||||
|
||||
## What Needs to Change
|
||||
|
||||
### File: `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`
|
||||
|
||||
Add two new NinjaScript properties:
|
||||
|
||||
```csharp
|
||||
// Kill switch — set to true in NT8 UI to flatten everything and stop trading
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Kill Switch (Flatten & Stop)", GroupName = "Emergency Controls", Order = 1)]
|
||||
public bool EnableKillSwitch { get; set; }
|
||||
|
||||
// Logging verbosity toggle
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Verbose Logging", GroupName = "Debug", Order = 1)]
|
||||
public bool EnableVerboseLogging { get; set; }
|
||||
```
|
||||
|
||||
Set defaults in `OnStateChange` → `State.SetDefaults`:
|
||||
```csharp
|
||||
EnableKillSwitch = false;
|
||||
EnableVerboseLogging = false;
|
||||
```
|
||||
|
||||
Add kill switch check at the TOP of `OnBarUpdate()`, BEFORE any strategy logic:
|
||||
```csharp
|
||||
protected override void OnBarUpdate()
|
||||
{
|
||||
if (BarsInProgress != 0) return;
|
||||
if (CurrentBar < BarsRequiredToTrade) return;
|
||||
|
||||
// Emergency kill switch — check FIRST, before anything else
|
||||
if (EnableKillSwitch)
|
||||
{
|
||||
if (!_killSwitchTriggered)
|
||||
{
|
||||
_killSwitchTriggered = true;
|
||||
Print(string.Format("[NT8-SDK] KILL SWITCH ACTIVATED at {0}. Flattening all positions.", Time[0]));
|
||||
|
||||
try
|
||||
{
|
||||
ExitLong("EmergencyFlatten");
|
||||
ExitShort("EmergencyFlatten");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Print(string.Format("[NT8-SDK] Error during emergency flatten: {0}", ex.Message));
|
||||
}
|
||||
}
|
||||
return; // Do not process any more bar logic
|
||||
}
|
||||
|
||||
// ... rest of OnBarUpdate
|
||||
}
|
||||
```
|
||||
|
||||
Add the tracking field:
|
||||
```csharp
|
||||
private bool _killSwitchTriggered = false;
|
||||
```
|
||||
|
||||
Reset in `OnStateChange` → `State.DataLoaded` or `State.Active`:
|
||||
```csharp
|
||||
_killSwitchTriggered = false;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `EnableKillSwitch` appears as a checkbox in the NT8 strategy parameter dialog under "Emergency Controls"
|
||||
- [ ] Setting `EnableKillSwitch = true` on a running strategy causes `ExitLong` and `ExitShort` to fire on the next bar
|
||||
- [ ] Once triggered, no new entries are made (strategy returns early every bar)
|
||||
- [ ] A `Print()` message confirms the activation with timestamp
|
||||
- [ ] Setting kill switch back to `false` does NOT re-enable trading in the same session (once triggered, stays triggered)
|
||||
- [ ] `EnableVerboseLogging` is exposed in parameter dialog under "Debug"
|
||||
- [ ] `verify-build.bat` passes
|
||||
|
||||
---
|
||||
|
||||
## Files to Modify
|
||||
|
||||
| File | Action |
|
||||
|---|---|
|
||||
| `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` | Add `EnableKillSwitch`, `EnableVerboseLogging` params; add kill switch logic to `OnBarUpdate()` |
|
||||
| `src/NT8.Adapters/Strategies/SimpleORBNT8.cs` | Ensure `EnableKillSwitch` is inherited (no changes needed if base class handles it) |
|
||||
|
||||
---
|
||||
|
||||
## Do NOT Change
|
||||
|
||||
- Any Core layer files
|
||||
- Any test files
|
||||
- Strategy logic in `SimpleORBStrategy.cs`
|
||||
116
docs/archive/completed-tasks/TASK_03_WIRE_CIRCUIT_BREAKER.md
Normal file
116
docs/archive/completed-tasks/TASK_03_WIRE_CIRCUIT_BREAKER.md
Normal file
@@ -0,0 +1,116 @@
|
||||
# Task 3 — Wire ExecutionCircuitBreaker
|
||||
|
||||
**Priority:** HIGH
|
||||
**Estimated time:** 1.5–2 hours
|
||||
**Depends on:** Task 1 (NT8StrategyBase changes)
|
||||
**Status:** TODO
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
`ExecutionCircuitBreaker` in `src/NT8.Core/Execution/ExecutionCircuitBreaker.cs` is a complete, well-tested class.
|
||||
It is never instantiated or connected to any live order flow. Orders are submitted regardless of latency or rejection conditions.
|
||||
|
||||
---
|
||||
|
||||
## What Needs to Change
|
||||
|
||||
### File: `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`
|
||||
|
||||
**Step 1:** Add `ExecutionCircuitBreaker` as a field on `NT8StrategyBase`.
|
||||
|
||||
```csharp
|
||||
private ExecutionCircuitBreaker _circuitBreaker;
|
||||
```
|
||||
|
||||
**Step 2:** Initialize it in `OnStateChange` → `State.DataLoaded`:
|
||||
```csharp
|
||||
// Use Microsoft.Extensions.Logging NullLogger for now (or wire to BasicLogger)
|
||||
_circuitBreaker = new ExecutionCircuitBreaker(
|
||||
new NullLogger<ExecutionCircuitBreaker>(),
|
||||
failureThreshold: 3,
|
||||
timeout: TimeSpan.FromSeconds(30));
|
||||
```
|
||||
|
||||
**Step 3:** Gate ALL order submissions through the circuit breaker.
|
||||
In the method that calls `ExecuteIntent()` (or wherever orders flow from strategy intent to the adapter), add:
|
||||
|
||||
```csharp
|
||||
private bool TrySubmitIntent(StrategyIntent intent, StrategyContext context)
|
||||
{
|
||||
if (!_circuitBreaker.ShouldAllowOrder())
|
||||
{
|
||||
var state = _circuitBreaker.GetState();
|
||||
Print(string.Format("[NT8-SDK] Circuit breaker OPEN — order blocked. Reason: {0}", state.Reason));
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_orderAdapter.ExecuteIntent(intent, context, _strategyConfig);
|
||||
_circuitBreaker.OnSuccess();
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_circuitBreaker.OnFailure();
|
||||
_circuitBreaker.RecordOrderRejection(ex.Message);
|
||||
Print(string.Format("[NT8-SDK] Order execution failed: {0}", ex.Message));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 4:** Wire `OnOrderUpdate` rejections back to the circuit breaker.
|
||||
In `NT8StrategyBase.OnOrderUpdate()`:
|
||||
```csharp
|
||||
protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice,
|
||||
int quantity, int filled, double averageFillPrice,
|
||||
OrderState orderState, DateTime time, ErrorCode error, string nativeError)
|
||||
{
|
||||
if (orderState == OrderState.Rejected)
|
||||
{
|
||||
if (_circuitBreaker != null)
|
||||
{
|
||||
_circuitBreaker.RecordOrderRejection(
|
||||
string.Format("NT8 rejected order: {0} {1}", error, nativeError));
|
||||
}
|
||||
}
|
||||
|
||||
// Pass through to adapter for state tracking
|
||||
if (_orderAdapter != null)
|
||||
{
|
||||
_orderAdapter.OnOrderUpdate(
|
||||
order != null ? order.Name : "unknown",
|
||||
limitPrice, stopPrice, quantity, filled,
|
||||
averageFillPrice,
|
||||
orderState != null ? orderState.ToString() : "unknown",
|
||||
time, error.ToString(), nativeError ?? string.Empty);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `ExecutionCircuitBreaker` is instantiated in `NT8StrategyBase`
|
||||
- [ ] All order submissions go through `_circuitBreaker.ShouldAllowOrder()` — if false, order is blocked and logged
|
||||
- [ ] NT8 order rejections call `_circuitBreaker.RecordOrderRejection()`
|
||||
- [ ] 3 consecutive rejections open the circuit breaker (blocks further orders for 30 seconds)
|
||||
- [ ] After 30 seconds, circuit breaker enters half-open and allows one test order
|
||||
- [ ] `verify-build.bat` passes
|
||||
|
||||
---
|
||||
|
||||
## Files to Modify
|
||||
|
||||
| File | Action |
|
||||
|---|---|
|
||||
| `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` | Add circuit breaker field, initialize, gate submissions, wire rejections |
|
||||
|
||||
## Files to NOT Change
|
||||
|
||||
- `src/NT8.Core/Execution/ExecutionCircuitBreaker.cs` — complete and correct, do not touch
|
||||
- Any test files
|
||||
184
docs/archive/fix-specs/BUILD_WARNINGS_REFERENCE.md
Normal file
184
docs/archive/fix-specs/BUILD_WARNINGS_REFERENCE.md
Normal file
@@ -0,0 +1,184 @@
|
||||
# Build Warnings - Quick Fix Guide
|
||||
|
||||
**Date:** February 15, 2026
|
||||
**Build Status:** ✅ SUCCESS (with warnings)
|
||||
|
||||
---
|
||||
|
||||
## Current Warnings Summary
|
||||
|
||||
### CS1998: Async method without await (12 occurrences)
|
||||
|
||||
**Location:**
|
||||
- `OrderManager.cs` (7 warnings)
|
||||
- `OrderManagerTests.cs` (2 warnings)
|
||||
|
||||
**Issue:** Methods marked as `async` but don't use `await`
|
||||
|
||||
**Fix Options:**
|
||||
|
||||
#### Option 1: Remove async if not needed
|
||||
```csharp
|
||||
// BEFORE (Warning)
|
||||
public async Task<string> MethodName()
|
||||
{
|
||||
return "result";
|
||||
}
|
||||
|
||||
// AFTER (Fixed)
|
||||
public Task<string> MethodName()
|
||||
{
|
||||
return Task.FromResult("result");
|
||||
}
|
||||
```
|
||||
|
||||
#### Option 2: Add await if async operation exists
|
||||
```csharp
|
||||
// If you have async operations
|
||||
public async Task<string> MethodName()
|
||||
{
|
||||
await SomeAsyncOperation();
|
||||
return "result";
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### CS0169/CS0414: Unused fields (5 occurrences)
|
||||
|
||||
**Location:** `SimpleORBNT8Wrapper.cs`
|
||||
|
||||
**Issue:** Fields declared but never used
|
||||
|
||||
**Fields:**
|
||||
- `_rangeSize`
|
||||
- `_openingRangeHigh`
|
||||
- `_openingRangeStart`
|
||||
- `_openingRangeLow`
|
||||
- `_openingRangeCalculated`
|
||||
|
||||
**Fix Options:**
|
||||
|
||||
#### Option 1: Remove if truly unused
|
||||
```csharp
|
||||
// Remove these lines if not needed:
|
||||
private double _openingRangeHigh;
|
||||
private double _openingRangeLow;
|
||||
```
|
||||
|
||||
#### Option 2: Use the fields
|
||||
```csharp
|
||||
// If you plan to use them, implement the logic
|
||||
private double _openingRangeHigh = 0;
|
||||
|
||||
void CalculateRange()
|
||||
{
|
||||
_openingRangeHigh = High[0]; // Use the field
|
||||
}
|
||||
```
|
||||
|
||||
#### Option 3: Suppress if placeholder for future
|
||||
```csharp
|
||||
#pragma warning disable CS0169
|
||||
private double _openingRangeHigh; // Will be used in Phase 2
|
||||
#pragma warning restore CS0169
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Action Items
|
||||
|
||||
### Priority 1: Critical for OMS
|
||||
❌ **None** - OMS implementation hasn't started yet
|
||||
|
||||
### Priority 2: Existing Code Cleanup
|
||||
These warnings are in **existing code** (not OMS):
|
||||
- `OrderManager.cs` - 7 async warnings
|
||||
- `SimpleORBNT8Wrapper.cs` - 5 unused field warnings
|
||||
- `OrderManagerTests.cs` - 2 async warnings
|
||||
|
||||
**Recommendation:** Fix these **after** OMS implementation to avoid modifying existing code.
|
||||
|
||||
---
|
||||
|
||||
## For Kilocode: Warning Rules
|
||||
|
||||
### ✅ ALLOWED: Warnings in existing code
|
||||
Kilocode can ignore warnings in:
|
||||
- `src/NT8.Adapters/**` (existing wrapper)
|
||||
- Existing `OrderManager.cs` (if it exists before OMS work)
|
||||
- Existing test files
|
||||
|
||||
### ❌ FORBIDDEN: Warnings in new OMS code
|
||||
Kilocode MUST NOT introduce warnings in new code:
|
||||
- New `src/NT8.Core/OMS/**` files
|
||||
- New `tests/NT8.Core.Tests/OMS/**` files
|
||||
|
||||
### Rule for Kilocode:
|
||||
```
|
||||
When creating new OMS files:
|
||||
- NO CS1998 warnings (remove async or add await)
|
||||
- NO CS0169/CS0414 warnings (use all declared fields)
|
||||
- Build with ZERO warnings for new code
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Build Verification
|
||||
|
||||
### Current Status
|
||||
```
|
||||
Build: ✅ SUCCESS
|
||||
Warnings: 17 total
|
||||
- 12 × CS1998 (async without await)
|
||||
- 5 × CS0169/CS0414 (unused fields)
|
||||
|
||||
All warnings in EXISTING code (not OMS)
|
||||
```
|
||||
|
||||
### Target for OMS
|
||||
```
|
||||
Build: ✅ SUCCESS
|
||||
New OMS files: ZERO warnings
|
||||
Existing warnings: Can remain (cleanup later)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick Fix Script (Optional)
|
||||
|
||||
If you want to clean up existing warnings before OMS work:
|
||||
|
||||
```powershell
|
||||
# Fix unused fields in SimpleORBNT8Wrapper.cs
|
||||
# Option 1: Comment out unused fields
|
||||
# Option 2: Implement ORB calculation logic
|
||||
# Option 3: Add #pragma warning disable
|
||||
|
||||
# Fix async warnings in OrderManager.cs
|
||||
# Review each method and either:
|
||||
# - Remove async keyword + return Task.FromResult()
|
||||
# - Add await operations
|
||||
# - Keep as-is if async needed for interface
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
**For OMS Implementation:**
|
||||
- ✅ Build is working correctly
|
||||
- ✅ Existing warnings are acceptable
|
||||
- ✅ Kilocode should NOT modify existing code
|
||||
- ✅ New OMS code must have ZERO warnings
|
||||
|
||||
**After OMS Complete:**
|
||||
- Clean up existing warnings
|
||||
- Review async patterns
|
||||
- Remove unused fields or implement them
|
||||
|
||||
---
|
||||
|
||||
**Build status: Ready for OMS implementation!** 🚀
|
||||
|
||||
The warnings are in existing code, not a blocker for starting OMS work.
|
||||
314
docs/archive/fix-specs/COMPILE_FIX_SPECIFICATION.md
Normal file
314
docs/archive/fix-specs/COMPILE_FIX_SPECIFICATION.md
Normal file
@@ -0,0 +1,314 @@
|
||||
# NT8 Compile Fix Specification
|
||||
|
||||
**For:** Kilocode AI Agent
|
||||
**Priority:** URGENT
|
||||
**Mode:** Code Mode
|
||||
**Estimated Time:** 30-45 minutes
|
||||
**Files to Edit:** 2 files
|
||||
**New Files:** 0
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Objective
|
||||
|
||||
Fix 9 NT8 NinjaScript compilation errors in two strategy files. These are
|
||||
mechanical fixes - naming conflicts, type conversions, and a missing reference.
|
||||
Do NOT redesign logic. Surgical edits only.
|
||||
|
||||
---
|
||||
|
||||
## 📋 Error Summary
|
||||
|
||||
| # | File | Error | Line | Fix Type |
|
||||
|---|------|-------|------|----------|
|
||||
| 1 | SimpleORBNT8.cs | `NT8.Strategies` namespace not found | 15 | Add using alias |
|
||||
| 2 | NT8StrategyBase.cs | `Position` ambiguous reference | 49 | Qualify type |
|
||||
| 3 | NT8StrategyBase.cs | `Position` ambiguous reference | 300 | Qualify type |
|
||||
| 4 | SimpleORBNT8.cs | `SimpleORBStrategy` not found | 72 | Add using alias |
|
||||
| 5 | NT8StrategyBase.cs | `double` cannot convert to `long` | 273 | Cast to long |
|
||||
| 6 | NT8StrategyBase.cs | `double` cannot convert to `int` | 364 | Cast to int |
|
||||
| 7 | NT8StrategyBase.cs | `double` cannot convert to `int` | 366 | Cast to int |
|
||||
| 8 | NT8StrategyBase.cs | `double` cannot convert to `int` | 373 | Cast to int |
|
||||
| 9 | NT8StrategyBase.cs | `double` cannot convert to `int` | 375 | Cast to int |
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Fix 1: NT8StrategyBase.cs - Ambiguous `Position` reference (Errors 2 & 3)
|
||||
|
||||
### Problem
|
||||
NT8's `NinjaTrader.Cbi.Position` and our `NT8.Core.Common.Models.Position` both exist
|
||||
in scope. C# cannot resolve which one to use on lines 49 and 300.
|
||||
|
||||
### Solution
|
||||
Add a using alias at the top of the file to disambiguate, then use the alias
|
||||
wherever SDK Position is intended.
|
||||
|
||||
### Change 1a: Add alias to using block (top of file, after existing using aliases)
|
||||
|
||||
**Find this block** (lines 19-25):
|
||||
```csharp
|
||||
using SdkOrderSide = NT8.Core.Common.Models.OrderSide;
|
||||
using SdkOrderType = NT8.Core.Common.Models.OrderType;
|
||||
using OmsOrderRequest = NT8.Core.OMS.OrderRequest;
|
||||
using OmsOrderSide = NT8.Core.OMS.OrderSide;
|
||||
using OmsOrderType = NT8.Core.OMS.OrderType;
|
||||
using OmsOrderState = NT8.Core.OMS.OrderState;
|
||||
using OmsOrderStatus = NT8.Core.OMS.OrderStatus;
|
||||
```
|
||||
|
||||
**Replace with** (add one line at top):
|
||||
```csharp
|
||||
using SdkPosition = NT8.Core.Common.Models.Position;
|
||||
using SdkOrderSide = NT8.Core.Common.Models.OrderSide;
|
||||
using SdkOrderType = NT8.Core.Common.Models.OrderType;
|
||||
using OmsOrderRequest = NT8.Core.OMS.OrderRequest;
|
||||
using OmsOrderSide = NT8.Core.OMS.OrderSide;
|
||||
using OmsOrderType = NT8.Core.OMS.OrderType;
|
||||
using OmsOrderState = NT8.Core.OMS.OrderState;
|
||||
using OmsOrderStatus = NT8.Core.OMS.OrderStatus;
|
||||
```
|
||||
|
||||
### Change 1b: Fix field declaration (line 49)
|
||||
|
||||
**Find:**
|
||||
```csharp
|
||||
private Position _lastPosition;
|
||||
```
|
||||
|
||||
**Replace with:**
|
||||
```csharp
|
||||
private SdkPosition _lastPosition;
|
||||
```
|
||||
|
||||
### Change 1c: Fix return type in BuildPositionInfo() (line 300 area)
|
||||
|
||||
**Find:**
|
||||
```csharp
|
||||
private Position BuildPositionInfo()
|
||||
{
|
||||
var p = NT8DataConverter.ConvertPosition(
|
||||
Instrument.MasterInstrument.Name,
|
||||
Position.Quantity,
|
||||
Position.AveragePrice,
|
||||
0.0,
|
||||
0.0,
|
||||
DateTime.UtcNow);
|
||||
|
||||
_lastPosition = p;
|
||||
return p;
|
||||
}
|
||||
```
|
||||
|
||||
**Replace with:**
|
||||
```csharp
|
||||
private SdkPosition BuildPositionInfo()
|
||||
{
|
||||
var p = NT8DataConverter.ConvertPosition(
|
||||
Instrument.MasterInstrument.Name,
|
||||
Position.Quantity,
|
||||
Position.AveragePrice,
|
||||
0.0,
|
||||
0.0,
|
||||
DateTime.UtcNow);
|
||||
|
||||
_lastPosition = p;
|
||||
return p;
|
||||
}
|
||||
```
|
||||
|
||||
**NOTE:** `Position.Quantity` and `Position.AveragePrice` (without qualifier) correctly
|
||||
refer to `NinjaTrader.Cbi.Position` (NT8's built-in position property on the Strategy
|
||||
class). Only the return type and field type need the alias. Do NOT change the
|
||||
`Position.Quantity` / `Position.AveragePrice` references.
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Fix 2: NT8StrategyBase.cs - Volume double to long (Error 5)
|
||||
|
||||
### Problem
|
||||
`NT8DataConverter.ConvertBar()` expects `volume` as `long`, but NT8's `Volume[0]`
|
||||
returns `double`.
|
||||
|
||||
### Location
|
||||
Inside `ConvertCurrentBar()` method (line 273 area).
|
||||
|
||||
### Change: Cast Volume[0] to long
|
||||
|
||||
**Find:**
|
||||
```csharp
|
||||
private BarData ConvertCurrentBar()
|
||||
{
|
||||
return NT8DataConverter.ConvertBar(
|
||||
Instrument.MasterInstrument.Name,
|
||||
Time[0],
|
||||
Open[0],
|
||||
High[0],
|
||||
Low[0],
|
||||
Close[0],
|
||||
Volume[0],
|
||||
(int)BarsPeriod.Value);
|
||||
}
|
||||
```
|
||||
|
||||
**Replace with:**
|
||||
```csharp
|
||||
private BarData ConvertCurrentBar()
|
||||
{
|
||||
return NT8DataConverter.ConvertBar(
|
||||
Instrument.MasterInstrument.Name,
|
||||
Time[0],
|
||||
Open[0],
|
||||
High[0],
|
||||
Low[0],
|
||||
Close[0],
|
||||
(long)Volume[0],
|
||||
(int)BarsPeriod.Value);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Fix 3: NT8StrategyBase.cs - StopTicks/TargetTicks double to int (Errors 6-9)
|
||||
|
||||
### Problem
|
||||
`SetStopLoss()` and `SetProfitTarget()` NT8 methods expect `int` for tick counts,
|
||||
but `intent.StopTicks` and `intent.TargetTicks` are `double`.
|
||||
|
||||
### Location
|
||||
Inside `SubmitOrderToNT8()` method (lines 364-375 area).
|
||||
|
||||
### Change: Cast tick values to int
|
||||
|
||||
**Find:**
|
||||
```csharp
|
||||
if (intent.StopTicks > 0)
|
||||
SetStopLoss(orderName, CalculationMode.Ticks, intent.StopTicks, false);
|
||||
|
||||
if (intent.TargetTicks.HasValue && intent.TargetTicks.Value > 0)
|
||||
SetProfitTarget(orderName, CalculationMode.Ticks, intent.TargetTicks.Value);
|
||||
```
|
||||
|
||||
**Replace with:**
|
||||
```csharp
|
||||
if (intent.StopTicks > 0)
|
||||
SetStopLoss(orderName, CalculationMode.Ticks, (int)intent.StopTicks, false);
|
||||
|
||||
if (intent.TargetTicks.HasValue && intent.TargetTicks.Value > 0)
|
||||
SetProfitTarget(orderName, CalculationMode.Ticks, (int)intent.TargetTicks.Value);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Fix 4: SimpleORBNT8.cs - Missing NT8.Strategies reference (Errors 1 & 4)
|
||||
|
||||
### Problem
|
||||
`SimpleORBStrategy` lives in the `NT8.Strategies.Examples` namespace. The using
|
||||
directive references `NT8.Strategies.Examples` but NT8.Strategies.dll must also be
|
||||
deployed to NT8 Custom folder AND added as a reference in the NinjaScript Editor.
|
||||
|
||||
### Change: Add using alias at top of SimpleORBNT8.cs
|
||||
|
||||
**Find** (line 15):
|
||||
```csharp
|
||||
using NT8.Strategies.Examples;
|
||||
```
|
||||
|
||||
**Replace with:**
|
||||
```csharp
|
||||
using NT8.Strategies.Examples;
|
||||
using SdkSimpleORB = NT8.Strategies.Examples.SimpleORBStrategy;
|
||||
```
|
||||
|
||||
**AND** update the usage inside `CreateSdkStrategy()`:
|
||||
|
||||
**Find:**
|
||||
```csharp
|
||||
protected override IStrategy CreateSdkStrategy()
|
||||
{
|
||||
return new SimpleORBStrategy(OpeningRangeMinutes, StdDevMultiplier);
|
||||
}
|
||||
```
|
||||
|
||||
**Replace with:**
|
||||
```csharp
|
||||
protected override IStrategy CreateSdkStrategy()
|
||||
{
|
||||
return new SdkSimpleORB(OpeningRangeMinutes, StdDevMultiplier);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📦 Deployment Step (Manual - Not Kilocode)
|
||||
|
||||
**After code fixes are committed**, Mo needs to:
|
||||
|
||||
```powershell
|
||||
# Build NT8.Strategies project
|
||||
cd C:\dev\nt8-sdk
|
||||
dotnet build src\NT8.Strategies\NT8.Strategies.csproj --configuration Release
|
||||
|
||||
# Copy DLL to NT8 Custom folder (NT8 must be closed)
|
||||
Copy-Item "src\NT8.Strategies\bin\Release\net48\NT8.Strategies.dll" `
|
||||
"$env:USERPROFILE\Documents\NinjaTrader 8\bin\Custom\" -Force
|
||||
```
|
||||
|
||||
Then in NT8 NinjaScript Editor:
|
||||
- Right-click → References → Add → NT8.Strategies.dll
|
||||
|
||||
---
|
||||
|
||||
## ✅ Verification Steps
|
||||
|
||||
### After Code Changes:
|
||||
```bash
|
||||
# Build must succeed with zero errors
|
||||
dotnet build src\NT8.Adapters\NT8.Adapters.csproj --configuration Release
|
||||
|
||||
# All tests must still pass
|
||||
dotnet test NT8-SDK.sln --configuration Release --no-build
|
||||
```
|
||||
|
||||
### After NT8 Recompile:
|
||||
- [ ] Zero compilation errors in NinjaScript Editor
|
||||
- [ ] MinimalTestStrategy visible in strategy list
|
||||
- [ ] SimpleORBNT8 visible in strategy list
|
||||
- [ ] NT8StrategyBase not directly visible (abstract)
|
||||
|
||||
---
|
||||
|
||||
## 🚨 Constraints
|
||||
|
||||
- C# 5.0 syntax only - no modern features
|
||||
- Surgical edits ONLY - do not refactor or redesign
|
||||
- Do NOT change any logic, only fix the type issues
|
||||
- Preserve all XML documentation comments
|
||||
- All 319 existing tests must still pass after changes
|
||||
|
||||
---
|
||||
|
||||
## 📋 Git Commit
|
||||
|
||||
```bash
|
||||
git add src/NT8.Adapters/Strategies/NT8StrategyBase.cs
|
||||
git add src/NT8.Adapters/Strategies/SimpleORBNT8.cs
|
||||
git commit -m "fix: Resolve NT8 NinjaScript compilation errors
|
||||
|
||||
- Add SdkPosition alias to disambiguate from NinjaTrader.Cbi.Position
|
||||
- Cast Volume[0] from double to long for ConvertBar()
|
||||
- Cast StopTicks/TargetTicks from double to int for SetStopLoss/SetProfitTarget
|
||||
- Add SdkSimpleORB alias for SimpleORBStrategy in SimpleORBNT8.cs
|
||||
|
||||
All 9 NT8 compile errors resolved. Zero logic changes."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Success Criteria
|
||||
|
||||
- [ ] Zero compilation errors in NT8 NinjaScript Editor
|
||||
- [ ] All 319 existing tests still passing
|
||||
- [ ] Zero new build warnings
|
||||
- [ ] Code committed to Git
|
||||
|
||||
**READY FOR KILOCODE - CODE MODE** ✅
|
||||
550
docs/archive/fix-specs/CONFIG_EXPORT_SPEC.md
Normal file
550
docs/archive/fix-specs/CONFIG_EXPORT_SPEC.md
Normal file
@@ -0,0 +1,550 @@
|
||||
# Configuration Export/Import - Implementation Specification
|
||||
|
||||
**For:** Kilocode AI Agent
|
||||
**Priority:** HIGH
|
||||
**Mode:** Code Mode
|
||||
**Estimated Time:** 1.5-2 hours
|
||||
**Files to Edit:** 1 file (NT8StrategyBase.cs)
|
||||
**Files to Create:** 1 file (StrategyConfigExporter.cs)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Objective
|
||||
|
||||
Add ability to export NT8 strategy configuration as JSON for:
|
||||
- Easy sharing with support/debugging
|
||||
- Version control of strategy settings
|
||||
- Configuration backup/restore
|
||||
- Reproducible backtests
|
||||
|
||||
---
|
||||
|
||||
## 📋 What We're Adding
|
||||
|
||||
### 1. Export Configuration Button/Method
|
||||
User can click a button (or call a method) to export all strategy settings as JSON file.
|
||||
|
||||
### 2. Import Configuration Method
|
||||
User can load settings from a previously exported JSON file.
|
||||
|
||||
### 3. Automatic Export on Strategy Start
|
||||
Optionally auto-export config to a timestamped file when strategy starts.
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Implementation
|
||||
|
||||
### Component 1: StrategyConfigExporter.cs
|
||||
|
||||
**Location:** `src/NT8.Adapters/Strategies/StrategyConfigExporter.cs`
|
||||
|
||||
**Purpose:** Static helper class to serialize/deserialize strategy configurations
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace NT8.Adapters.Strategies
|
||||
{
|
||||
/// <summary>
|
||||
/// Helper class to export/import NT8 strategy configurations as JSON.
|
||||
/// Enables configuration sharing, backup, and reproducible testing.
|
||||
/// </summary>
|
||||
public static class StrategyConfigExporter
|
||||
{
|
||||
/// <summary>
|
||||
/// Export strategy configuration to JSON string.
|
||||
/// </summary>
|
||||
public static string ExportToJson(Dictionary<string, object> config)
|
||||
{
|
||||
if (config == null || config.Count == 0)
|
||||
return "{}";
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine("{");
|
||||
|
||||
var first = true;
|
||||
foreach (var kvp in config)
|
||||
{
|
||||
if (!first)
|
||||
sb.AppendLine(",");
|
||||
first = false;
|
||||
|
||||
sb.Append(" \"");
|
||||
sb.Append(EscapeJsonString(kvp.Key));
|
||||
sb.Append("\": ");
|
||||
|
||||
AppendValue(sb, kvp.Value);
|
||||
}
|
||||
|
||||
sb.AppendLine();
|
||||
sb.Append("}");
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Save configuration to JSON file.
|
||||
/// </summary>
|
||||
public static void ExportToFile(Dictionary<string, object> config, string filepath)
|
||||
{
|
||||
var json = ExportToJson(config);
|
||||
File.WriteAllText(filepath, json);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Import configuration from JSON string.
|
||||
/// Simple parser for basic types (string, int, double, bool).
|
||||
/// </summary>
|
||||
public static Dictionary<string, object> ImportFromJson(string json)
|
||||
{
|
||||
var config = new Dictionary<string, object>();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
return config;
|
||||
|
||||
// Remove outer braces and whitespace
|
||||
json = json.Trim();
|
||||
if (json.StartsWith("{"))
|
||||
json = json.Substring(1);
|
||||
if (json.EndsWith("}"))
|
||||
json = json.Substring(0, json.Length - 1);
|
||||
|
||||
// Split by commas (simple parser - doesn't handle nested objects)
|
||||
var lines = json.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var colonIndex = line.IndexOf(':');
|
||||
if (colonIndex < 0)
|
||||
continue;
|
||||
|
||||
var key = line.Substring(0, colonIndex).Trim().Trim('"');
|
||||
var valueStr = line.Substring(colonIndex + 1).Trim();
|
||||
|
||||
var value = ParseValue(valueStr);
|
||||
config[key] = value;
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Import configuration from JSON file.
|
||||
/// </summary>
|
||||
public static Dictionary<string, object> ImportFromFile(string filepath)
|
||||
{
|
||||
if (!File.Exists(filepath))
|
||||
throw new FileNotFoundException("Config file not found", filepath);
|
||||
|
||||
var json = File.ReadAllText(filepath);
|
||||
return ImportFromJson(json);
|
||||
}
|
||||
|
||||
#region Helper Methods
|
||||
|
||||
private static void AppendValue(StringBuilder sb, object value)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
sb.Append("null");
|
||||
}
|
||||
else if (value is string)
|
||||
{
|
||||
sb.Append("\"");
|
||||
sb.Append(EscapeJsonString(value.ToString()));
|
||||
sb.Append("\"");
|
||||
}
|
||||
else if (value is bool)
|
||||
{
|
||||
sb.Append(((bool)value) ? "true" : "false");
|
||||
}
|
||||
else if (value is int || value is long || value is double || value is decimal || value is float)
|
||||
{
|
||||
sb.Append(value.ToString());
|
||||
}
|
||||
else if (value is DateTime)
|
||||
{
|
||||
sb.Append("\"");
|
||||
sb.Append(((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"));
|
||||
sb.Append("\"");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Fallback: ToString()
|
||||
sb.Append("\"");
|
||||
sb.Append(EscapeJsonString(value.ToString()));
|
||||
sb.Append("\"");
|
||||
}
|
||||
}
|
||||
|
||||
private static string EscapeJsonString(string str)
|
||||
{
|
||||
if (string.IsNullOrEmpty(str))
|
||||
return str;
|
||||
|
||||
return str
|
||||
.Replace("\\", "\\\\")
|
||||
.Replace("\"", "\\\"")
|
||||
.Replace("\n", "\\n")
|
||||
.Replace("\r", "\\r")
|
||||
.Replace("\t", "\\t");
|
||||
}
|
||||
|
||||
private static object ParseValue(string valueStr)
|
||||
{
|
||||
valueStr = valueStr.Trim();
|
||||
|
||||
// Remove trailing comma if present
|
||||
if (valueStr.EndsWith(","))
|
||||
valueStr = valueStr.Substring(0, valueStr.Length - 1).Trim();
|
||||
|
||||
// Null
|
||||
if (valueStr == "null")
|
||||
return null;
|
||||
|
||||
// Boolean
|
||||
if (valueStr == "true")
|
||||
return true;
|
||||
if (valueStr == "false")
|
||||
return false;
|
||||
|
||||
// String (quoted)
|
||||
if (valueStr.StartsWith("\"") && valueStr.EndsWith("\""))
|
||||
{
|
||||
var str = valueStr.Substring(1, valueStr.Length - 2);
|
||||
return UnescapeJsonString(str);
|
||||
}
|
||||
|
||||
// Number - try int, then double
|
||||
int intVal;
|
||||
if (int.TryParse(valueStr, out intVal))
|
||||
return intVal;
|
||||
|
||||
double doubleVal;
|
||||
if (double.TryParse(valueStr, out doubleVal))
|
||||
return doubleVal;
|
||||
|
||||
// Fallback: return as string
|
||||
return valueStr;
|
||||
}
|
||||
|
||||
private static string UnescapeJsonString(string str)
|
||||
{
|
||||
if (string.IsNullOrEmpty(str))
|
||||
return str;
|
||||
|
||||
return str
|
||||
.Replace("\\\"", "\"")
|
||||
.Replace("\\\\", "\\")
|
||||
.Replace("\\n", "\n")
|
||||
.Replace("\\r", "\r")
|
||||
.Replace("\\t", "\t");
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Component 2: Add Export Methods to NT8StrategyBase.cs
|
||||
|
||||
**File:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`
|
||||
|
||||
**Add these properties and methods:**
|
||||
|
||||
```csharp
|
||||
#region Configuration Export/Import
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Auto Export Config", GroupName = "SDK", Order = 10)]
|
||||
public bool AutoExportConfig { get; set; }
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Config Export Path", GroupName = "SDK", Order = 11)]
|
||||
public string ConfigExportPath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Export current strategy configuration to JSON string.
|
||||
/// Can be called from derived strategies or used for debugging.
|
||||
/// </summary>
|
||||
public string ExportConfigurationJson()
|
||||
{
|
||||
var config = new Dictionary<string, object>();
|
||||
|
||||
// Basic info
|
||||
config["StrategyName"] = Name;
|
||||
config["ExportedAt"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
config["Instrument"] = Instrument != null ? Instrument.FullName : "Not Set";
|
||||
config["BarsPeriod"] = BarsPeriod != null ? BarsPeriod.ToString() : "Not Set";
|
||||
|
||||
// SDK settings
|
||||
config["EnableSDK"] = EnableSDK;
|
||||
config["AutoExportConfig"] = AutoExportConfig;
|
||||
config["ConfigExportPath"] = ConfigExportPath ?? "";
|
||||
|
||||
// Risk settings
|
||||
config["DailyLossLimit"] = DailyLossLimit;
|
||||
config["MaxTradeRisk"] = MaxTradeRisk;
|
||||
config["MaxOpenPositions"] = MaxOpenPositions;
|
||||
|
||||
// Sizing settings
|
||||
config["RiskPerTrade"] = RiskPerTrade;
|
||||
config["MinContracts"] = MinContracts;
|
||||
config["MaxContracts"] = MaxContracts;
|
||||
|
||||
// NT8 settings
|
||||
config["BarsRequiredToTrade"] = BarsRequiredToTrade;
|
||||
config["Calculate"] = Calculate.ToString();
|
||||
config["EntriesPerDirection"] = EntriesPerDirection;
|
||||
config["StartBehavior"] = StartBehavior.ToString();
|
||||
|
||||
return StrategyConfigExporter.ExportToJson(config);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Export configuration to file.
|
||||
/// </summary>
|
||||
public void ExportConfigurationToFile(string filepath)
|
||||
{
|
||||
var config = GetConfigurationDictionary();
|
||||
StrategyConfigExporter.ExportToFile(config, filepath);
|
||||
Print(string.Format("[SDK] Configuration exported to: {0}", filepath));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get configuration as dictionary for export.
|
||||
/// </summary>
|
||||
protected Dictionary<string, object> GetConfigurationDictionary()
|
||||
{
|
||||
var config = new Dictionary<string, object>();
|
||||
|
||||
config["StrategyName"] = Name;
|
||||
config["ExportedAt"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
config["Instrument"] = Instrument != null ? Instrument.FullName : "Not Set";
|
||||
config["BarsPeriod"] = BarsPeriod != null ? BarsPeriod.ToString() : "Not Set";
|
||||
|
||||
config["EnableSDK"] = EnableSDK;
|
||||
config["AutoExportConfig"] = AutoExportConfig;
|
||||
config["ConfigExportPath"] = ConfigExportPath ?? "";
|
||||
|
||||
config["DailyLossLimit"] = DailyLossLimit;
|
||||
config["MaxTradeRisk"] = MaxTradeRisk;
|
||||
config["MaxOpenPositions"] = MaxOpenPositions;
|
||||
|
||||
config["RiskPerTrade"] = RiskPerTrade;
|
||||
config["MinContracts"] = MinContracts;
|
||||
config["MaxContracts"] = MaxContracts;
|
||||
|
||||
config["BarsRequiredToTrade"] = BarsRequiredToTrade;
|
||||
config["Calculate"] = Calculate.ToString();
|
||||
config["EntriesPerDirection"] = EntriesPerDirection;
|
||||
config["StartBehavior"] = StartBehavior.ToString();
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Print configuration to Output window for easy copy/paste.
|
||||
/// </summary>
|
||||
public void PrintConfiguration()
|
||||
{
|
||||
var json = ExportConfigurationJson();
|
||||
Print("=== Strategy Configuration ===");
|
||||
Print(json);
|
||||
Print("=== End Configuration ===");
|
||||
}
|
||||
|
||||
#endregion
|
||||
```
|
||||
|
||||
**Update OnStateChange() to handle auto-export:**
|
||||
|
||||
Find the `State.DataLoaded` section and add auto-export:
|
||||
|
||||
```csharp
|
||||
else if (State == State.DataLoaded)
|
||||
{
|
||||
if (EnableSDK)
|
||||
{
|
||||
try
|
||||
{
|
||||
InitializeSdkComponents();
|
||||
_sdkInitialized = true;
|
||||
|
||||
Print(string.Format("[SDK] {0} initialized successfully", Name));
|
||||
|
||||
// Auto-export configuration if enabled
|
||||
if (AutoExportConfig)
|
||||
{
|
||||
var exportPath = ConfigExportPath;
|
||||
|
||||
// Default path if not specified
|
||||
if (string.IsNullOrEmpty(exportPath))
|
||||
{
|
||||
var timestamp = DateTime.Now.ToString("yyyyMMdd-HHmmss");
|
||||
var filename = string.Format("{0}_{1}_config.json", Name, timestamp);
|
||||
exportPath = System.IO.Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
|
||||
"NinjaTrader 8",
|
||||
"logs",
|
||||
filename
|
||||
);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
ExportConfigurationToFile(exportPath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Print(string.Format("[SDK] Failed to export config: {0}", ex.Message));
|
||||
}
|
||||
}
|
||||
|
||||
// Print config to Output window for easy access
|
||||
PrintConfiguration();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Print(string.Format("[SDK ERROR] Initialization failed: {0}", ex.Message));
|
||||
Log(string.Format("[SDK ERROR] {0}", ex.ToString()), LogLevel.Error);
|
||||
_sdkInitialized = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Update State.SetDefaults to include new properties:**
|
||||
|
||||
```csharp
|
||||
if (State == State.SetDefaults)
|
||||
{
|
||||
// ... existing code ...
|
||||
|
||||
// SDK configuration export
|
||||
AutoExportConfig = false; // Off by default
|
||||
ConfigExportPath = ""; // Empty = auto-generate path
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Component 3: Update SimpleORBNT8.cs
|
||||
|
||||
**Add SimpleORB-specific configuration export:**
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Export SimpleORB-specific configuration.
|
||||
/// Overrides base to include ORB parameters.
|
||||
/// </summary>
|
||||
protected new Dictionary<string, object> GetConfigurationDictionary()
|
||||
{
|
||||
var config = base.GetConfigurationDictionary();
|
||||
|
||||
// Add ORB-specific settings
|
||||
config["OpeningRangeMinutes"] = OpeningRangeMinutes;
|
||||
config["StdDevMultiplier"] = StdDevMultiplier;
|
||||
config["StopTicks"] = StopTicks;
|
||||
config["TargetTicks"] = TargetTicks;
|
||||
|
||||
return config;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Verification
|
||||
|
||||
### Manual Test
|
||||
|
||||
1. **Build:**
|
||||
```bash
|
||||
dotnet build src\NT8.Adapters\NT8.Adapters.csproj --configuration Release
|
||||
```
|
||||
|
||||
2. **Deploy:**
|
||||
```powershell
|
||||
.\deployment\Deploy-To-NT8.ps1
|
||||
```
|
||||
|
||||
3. **Test in NT8:**
|
||||
- Add SimpleORBNT8 to Strategy Analyzer
|
||||
- Enable strategy
|
||||
- Check Output window - should see:
|
||||
```
|
||||
[SDK] Simple ORB NT8 initialized successfully
|
||||
=== Strategy Configuration ===
|
||||
{
|
||||
"StrategyName": "Simple ORB NT8",
|
||||
"ExportedAt": "2026-02-17 14:30:00",
|
||||
"Instrument": "ES 03-26",
|
||||
"BarsPeriod": "5 Minute",
|
||||
"EnableSDK": true,
|
||||
"DailyLossLimit": 1000,
|
||||
...
|
||||
}
|
||||
=== End Configuration ===
|
||||
```
|
||||
|
||||
4. **Copy JSON from Output window** - ready to share!
|
||||
|
||||
5. **Test Auto-Export:**
|
||||
- Set `AutoExportConfig = true`
|
||||
- Re-enable strategy
|
||||
- Check `Documents\NinjaTrader 8\logs\` folder
|
||||
- Should see `SimpleORBNT8_[timestamp]_config.json`
|
||||
|
||||
---
|
||||
|
||||
## 📋 Success Criteria
|
||||
|
||||
- [ ] StrategyConfigExporter.cs created
|
||||
- [ ] Export methods added to NT8StrategyBase
|
||||
- [ ] Auto-export on strategy start works
|
||||
- [ ] PrintConfiguration() shows JSON in Output window
|
||||
- [ ] SimpleORBNT8 includes ORB-specific parameters
|
||||
- [ ] JSON format is valid and readable
|
||||
- [ ] Zero compilation errors
|
||||
- [ ] All 319 existing tests still pass
|
||||
|
||||
---
|
||||
|
||||
## 🚨 Constraints
|
||||
|
||||
- C# 5.0 syntax only (no modern JSON libraries)
|
||||
- Simple manual JSON serialization (no Newtonsoft.Json dependency)
|
||||
- Thread-safe (no async file I/O)
|
||||
- Minimal allocations
|
||||
- Clear error messages
|
||||
|
||||
---
|
||||
|
||||
## 📋 Git Commit
|
||||
|
||||
```bash
|
||||
git add src/NT8.Adapters/Strategies/StrategyConfigExporter.cs
|
||||
git add src/NT8.Adapters/Strategies/NT8StrategyBase.cs
|
||||
git add src/NT8.Adapters/Strategies/SimpleORBNT8.cs
|
||||
git commit -m "feat: Add configuration export/import
|
||||
|
||||
- Add StrategyConfigExporter helper class
|
||||
- Add ExportConfigurationJson() method
|
||||
- Add PrintConfiguration() to Output window
|
||||
- Add auto-export on strategy start
|
||||
- Add AutoExportConfig property
|
||||
- Simple JSON serialization (C# 5.0 compatible)
|
||||
|
||||
Enables easy configuration sharing for debugging"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**READY FOR KILOCODE - CODE MODE** ✅
|
||||
|
||||
**Time: 1.5-2 hours**
|
||||
276
docs/archive/fix-specs/DIAGNOSTIC_LOGGING_SPEC.md
Normal file
276
docs/archive/fix-specs/DIAGNOSTIC_LOGGING_SPEC.md
Normal file
@@ -0,0 +1,276 @@
|
||||
# NT8 Strategy Diagnostic Logging Enhancement
|
||||
|
||||
**For:** Kilocode AI Agent
|
||||
**Priority:** HIGH
|
||||
**Mode:** Code Mode
|
||||
**Estimated Time:** 30-40 minutes
|
||||
**Files to Edit:** 1 file (NT8StrategyBase.cs)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Objective
|
||||
|
||||
Add comprehensive diagnostic logging to NT8StrategyBase so we can see exactly
|
||||
what's happening during backtesting when zero trades occur. This will help
|
||||
diagnose if the issue is:
|
||||
- Strategy not generating intents
|
||||
- Risk manager rejecting trades
|
||||
- Position sizer issues
|
||||
- Data feed issues
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Changes to NT8StrategyBase.cs
|
||||
|
||||
### Change 1: Enhanced OnBarUpdate logging
|
||||
|
||||
**Find:**
|
||||
```csharp
|
||||
protected override void OnBarUpdate()
|
||||
{
|
||||
if (!_sdkInitialized || _sdkStrategy == null)
|
||||
return;
|
||||
if (CurrentBar < BarsRequiredToTrade)
|
||||
return;
|
||||
if (Time[0] == _lastBarTime)
|
||||
return;
|
||||
|
||||
_lastBarTime = Time[0];
|
||||
|
||||
try
|
||||
{
|
||||
var barData = ConvertCurrentBar();
|
||||
var context = BuildStrategyContext();
|
||||
|
||||
StrategyIntent intent;
|
||||
lock (_lock)
|
||||
{
|
||||
intent = _sdkStrategy.OnBar(barData, context);
|
||||
}
|
||||
|
||||
if (intent != null)
|
||||
ProcessStrategyIntent(intent, context);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_logger != null)
|
||||
_logger.LogError("OnBarUpdate failed: {0}", ex.Message);
|
||||
|
||||
Print(string.Format("[SDK ERROR] OnBarUpdate: {0}", ex.Message));
|
||||
Log(string.Format("[SDK ERROR] {0}", ex.ToString()), LogLevel.Error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Replace with:**
|
||||
```csharp
|
||||
protected override void OnBarUpdate()
|
||||
{
|
||||
if (!_sdkInitialized || _sdkStrategy == null)
|
||||
{
|
||||
if (CurrentBar == 0)
|
||||
Print(string.Format("[SDK] Not initialized: sdkInit={0}, strategy={1}",
|
||||
_sdkInitialized, _sdkStrategy != null));
|
||||
return;
|
||||
}
|
||||
|
||||
if (CurrentBar < BarsRequiredToTrade)
|
||||
{
|
||||
if (CurrentBar == 0)
|
||||
Print(string.Format("[SDK] Waiting for bars: current={0}, required={1}",
|
||||
CurrentBar, BarsRequiredToTrade));
|
||||
return;
|
||||
}
|
||||
|
||||
if (Time[0] == _lastBarTime)
|
||||
return;
|
||||
|
||||
_lastBarTime = Time[0];
|
||||
|
||||
// Log first bar and every 100th bar to show activity
|
||||
if (CurrentBar == BarsRequiredToTrade || CurrentBar % 100 == 0)
|
||||
{
|
||||
Print(string.Format("[SDK] Processing bar {0}: {1} O={2:F2} H={3:F2} L={4:F2} C={5:F2}",
|
||||
CurrentBar, Time[0].ToString("yyyy-MM-dd HH:mm"),
|
||||
Open[0], High[0], Low[0], Close[0]));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var barData = ConvertCurrentBar();
|
||||
var context = BuildStrategyContext();
|
||||
|
||||
StrategyIntent intent;
|
||||
lock (_lock)
|
||||
{
|
||||
intent = _sdkStrategy.OnBar(barData, context);
|
||||
}
|
||||
|
||||
if (intent != null)
|
||||
{
|
||||
Print(string.Format("[SDK] Intent generated: {0} {1} @ {2}",
|
||||
intent.Side, intent.Symbol, intent.EntryType));
|
||||
ProcessStrategyIntent(intent, context);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_logger != null)
|
||||
_logger.LogError("OnBarUpdate failed: {0}", ex.Message);
|
||||
|
||||
Print(string.Format("[SDK ERROR] OnBarUpdate: {0}", ex.Message));
|
||||
Log(string.Format("[SDK ERROR] {0}", ex.ToString()), LogLevel.Error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Change 2: Enhanced ProcessStrategyIntent logging
|
||||
|
||||
**Find:**
|
||||
```csharp
|
||||
private void ProcessStrategyIntent(StrategyIntent intent, StrategyContext context)
|
||||
{
|
||||
var riskDecision = _riskManager.ValidateOrder(intent, context, _riskConfig);
|
||||
if (!riskDecision.Allow)
|
||||
{
|
||||
if (_logger != null)
|
||||
_logger.LogWarning("Intent rejected by risk manager: {0}", riskDecision.RejectReason);
|
||||
return;
|
||||
}
|
||||
|
||||
var sizingResult = _positionSizer.CalculateSize(intent, context, _sizingConfig);
|
||||
if (sizingResult.Contracts < MinContracts)
|
||||
return;
|
||||
|
||||
var request = new OmsOrderRequest();
|
||||
request.Symbol = intent.Symbol;
|
||||
request.Side = MapOrderSide(intent.Side);
|
||||
request.Type = MapOrderType(intent.EntryType);
|
||||
request.Quantity = sizingResult.Contracts;
|
||||
request.LimitPrice = intent.LimitPrice.HasValue ? (decimal?)intent.LimitPrice.Value : null;
|
||||
request.StopPrice = null;
|
||||
|
||||
SubmitOrderToNT8(request, intent);
|
||||
_ordersSubmittedToday++;
|
||||
}
|
||||
```
|
||||
|
||||
**Replace with:**
|
||||
```csharp
|
||||
private void ProcessStrategyIntent(StrategyIntent intent, StrategyContext context)
|
||||
{
|
||||
Print(string.Format("[SDK] Validating intent: {0} {1}", intent.Side, intent.Symbol));
|
||||
|
||||
var riskDecision = _riskManager.ValidateOrder(intent, context, _riskConfig);
|
||||
if (!riskDecision.Allow)
|
||||
{
|
||||
Print(string.Format("[SDK] Risk REJECTED: {0}", riskDecision.RejectReason));
|
||||
if (_logger != null)
|
||||
_logger.LogWarning("Intent rejected by risk manager: {0}", riskDecision.RejectReason);
|
||||
return;
|
||||
}
|
||||
|
||||
Print(string.Format("[SDK] Risk approved"));
|
||||
|
||||
var sizingResult = _positionSizer.CalculateSize(intent, context, _sizingConfig);
|
||||
Print(string.Format("[SDK] Position size: {0} contracts (min={1}, max={2})",
|
||||
sizingResult.Contracts, MinContracts, MaxContracts));
|
||||
|
||||
if (sizingResult.Contracts < MinContracts)
|
||||
{
|
||||
Print(string.Format("[SDK] Size too small: {0} < {1}", sizingResult.Contracts, MinContracts));
|
||||
return;
|
||||
}
|
||||
|
||||
var request = new OmsOrderRequest();
|
||||
request.Symbol = intent.Symbol;
|
||||
request.Side = MapOrderSide(intent.Side);
|
||||
request.Type = MapOrderType(intent.EntryType);
|
||||
request.Quantity = sizingResult.Contracts;
|
||||
request.LimitPrice = intent.LimitPrice.HasValue ? (decimal?)intent.LimitPrice.Value : null;
|
||||
request.StopPrice = null;
|
||||
|
||||
Print(string.Format("[SDK] Submitting order: {0} {1} {2} @ {3}",
|
||||
request.Side, request.Quantity, request.Symbol, request.Type));
|
||||
|
||||
SubmitOrderToNT8(request, intent);
|
||||
_ordersSubmittedToday++;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Change 3: Enhanced InitializeSdkComponents logging
|
||||
|
||||
**Find:**
|
||||
```csharp
|
||||
private void InitializeSdkComponents()
|
||||
{
|
||||
_logger = new BasicLogger(Name);
|
||||
|
||||
_riskConfig = new RiskConfig(DailyLossLimit, MaxTradeRisk, MaxOpenPositions, true);
|
||||
```
|
||||
|
||||
**Replace with:**
|
||||
```csharp
|
||||
private void InitializeSdkComponents()
|
||||
{
|
||||
_logger = new BasicLogger(Name);
|
||||
|
||||
Print(string.Format("[SDK] Initializing with: DailyLoss={0:C}, TradeRisk={1:C}, MaxPos={2}",
|
||||
DailyLossLimit, MaxTradeRisk, MaxOpenPositions));
|
||||
|
||||
_riskConfig = new RiskConfig(DailyLossLimit, MaxTradeRisk, MaxOpenPositions, true);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Verification
|
||||
|
||||
```bash
|
||||
# Build must succeed
|
||||
dotnet build src\NT8.Adapters\NT8.Adapters.csproj --configuration Release
|
||||
|
||||
# Deploy
|
||||
.\deployment\Deploy-To-NT8.ps1
|
||||
```
|
||||
|
||||
**Expected in NT8 Output Window after backtest:**
|
||||
```
|
||||
[SDK] Initializing with: DailyLoss=$1,000.00, TradeRisk=$200.00, MaxPos=3
|
||||
[SDK] Simple ORB NT8 initialized successfully
|
||||
[SDK] Waiting for bars: current=0, required=50
|
||||
[SDK] Processing bar 50: 2026-02-10 09:30 O=4200.00 H=4210.00 L=4195.00 C=4208.00
|
||||
[SDK] Processing bar 150: 2026-02-10 12:30 O=4215.00 H=4220.00 L=4210.00 C=4218.00
|
||||
[SDK] Intent generated: Buy ES @ Market
|
||||
[SDK] Validating intent: Buy ES
|
||||
[SDK] Risk approved
|
||||
[SDK] Position size: 1 contracts (min=1, max=3)
|
||||
[SDK] Submitting order: Buy 1 ES @ Market
|
||||
```
|
||||
|
||||
This will show exactly where the strategy is failing.
|
||||
|
||||
---
|
||||
|
||||
## 📋 Git Commit
|
||||
|
||||
```bash
|
||||
git add src/NT8.Adapters/Strategies/NT8StrategyBase.cs
|
||||
git commit -m "feat: Add comprehensive diagnostic logging
|
||||
|
||||
- Log initialization parameters
|
||||
- Log bar processing activity (every 100 bars)
|
||||
- Log intent generation
|
||||
- Log risk validation results
|
||||
- Log position sizing calculations
|
||||
- Log order submission
|
||||
|
||||
Makes it easy to diagnose why strategy isn't trading"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**READY FOR KILOCODE - CODE MODE** ✅
|
||||
152
docs/archive/fix-specs/DROPDOWN_FIX_SPECIFICATION.md
Normal file
152
docs/archive/fix-specs/DROPDOWN_FIX_SPECIFICATION.md
Normal file
@@ -0,0 +1,152 @@
|
||||
# NT8 Strategy Dropdown Fix Specification
|
||||
|
||||
**For:** Kilocode AI Agent
|
||||
**Priority:** URGENT
|
||||
**Mode:** Code Mode
|
||||
**Estimated Time:** 20-30 minutes
|
||||
**Files to Edit:** 1 file (SimpleORBNT8.cs)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Objective
|
||||
|
||||
Fix SimpleORBNT8 not appearing in NT8 strategy dropdown. The strategy compiles
|
||||
but causes a runtime error when NT8 tries to load it for the dropdown list.
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Root Cause
|
||||
|
||||
`ConfigureStrategyParameters()` is called during `State.DataLoaded` and accesses
|
||||
`Instrument.MasterInstrument.PointValue` and `Instrument.MasterInstrument.TickSize`.
|
||||
|
||||
These properties are only safely available when the strategy is applied to a chart
|
||||
with a known instrument. When NT8 loads the strategy list for the dropdown,
|
||||
`Instrument` is null, causing a NullReferenceException that removes the strategy
|
||||
from the available list silently.
|
||||
|
||||
Per NT8 forum: "If there is an error in OnStateChange() when you go to
|
||||
New > Strategy, the OnStateChange() is called and a run-time type error
|
||||
can occur which removes the strategy from the available list as a preventative measure."
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Fix: SimpleORBNT8.cs - Guard Instrument access
|
||||
|
||||
### File
|
||||
`src/NT8.Adapters/Strategies/SimpleORBNT8.cs`
|
||||
|
||||
### Change: Add null guard in ConfigureStrategyParameters()
|
||||
|
||||
**Find:**
|
||||
```csharp
|
||||
protected override void ConfigureStrategyParameters()
|
||||
{
|
||||
_strategyConfig.RiskSettings.DailyLossLimit = DailyLossLimit;
|
||||
_strategyConfig.RiskSettings.MaxTradeRisk = MaxTradeRisk;
|
||||
_strategyConfig.RiskSettings.MaxOpenPositions = MaxOpenPositions;
|
||||
|
||||
var pointValue = Instrument.MasterInstrument.PointValue;
|
||||
var tickSize = Instrument.MasterInstrument.TickSize;
|
||||
var dollarRisk = StopTicks * tickSize * pointValue;
|
||||
|
||||
if (dollarRisk > _strategyConfig.RiskSettings.MaxTradeRisk)
|
||||
_strategyConfig.RiskSettings.MaxTradeRisk = dollarRisk;
|
||||
|
||||
_strategyConfig.SizingSettings.RiskPerTrade = RiskPerTrade;
|
||||
_strategyConfig.SizingSettings.MinContracts = MinContracts;
|
||||
_strategyConfig.SizingSettings.MaxContracts = MaxContracts;
|
||||
|
||||
_strategyConfig.Parameters["StopTicks"] = StopTicks;
|
||||
_strategyConfig.Parameters["TargetTicks"] = TargetTicks;
|
||||
_strategyConfig.Parameters["OpeningRangeMinutes"] = OpeningRangeMinutes;
|
||||
|
||||
if (_logger != null)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Simple ORB configured: OR={0}min, Stop={1}ticks, Target={2}ticks",
|
||||
OpeningRangeMinutes,
|
||||
StopTicks,
|
||||
TargetTicks);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Replace with:**
|
||||
```csharp
|
||||
protected override void ConfigureStrategyParameters()
|
||||
{
|
||||
_strategyConfig.RiskSettings.DailyLossLimit = DailyLossLimit;
|
||||
_strategyConfig.RiskSettings.MaxTradeRisk = MaxTradeRisk;
|
||||
_strategyConfig.RiskSettings.MaxOpenPositions = MaxOpenPositions;
|
||||
|
||||
// Guard: Instrument may be null during strategy list loading
|
||||
if (Instrument != null && Instrument.MasterInstrument != null)
|
||||
{
|
||||
var pointValue = Instrument.MasterInstrument.PointValue;
|
||||
var tickSize = Instrument.MasterInstrument.TickSize;
|
||||
var dollarRisk = StopTicks * tickSize * pointValue;
|
||||
|
||||
if (dollarRisk > _strategyConfig.RiskSettings.MaxTradeRisk)
|
||||
_strategyConfig.RiskSettings.MaxTradeRisk = dollarRisk;
|
||||
}
|
||||
|
||||
_strategyConfig.SizingSettings.RiskPerTrade = RiskPerTrade;
|
||||
_strategyConfig.SizingSettings.MinContracts = MinContracts;
|
||||
_strategyConfig.SizingSettings.MaxContracts = MaxContracts;
|
||||
|
||||
_strategyConfig.Parameters["StopTicks"] = StopTicks;
|
||||
_strategyConfig.Parameters["TargetTicks"] = TargetTicks;
|
||||
_strategyConfig.Parameters["OpeningRangeMinutes"] = OpeningRangeMinutes;
|
||||
|
||||
if (_logger != null)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Simple ORB configured: OR={0}min, Stop={1}ticks, Target={2}ticks",
|
||||
OpeningRangeMinutes,
|
||||
StopTicks,
|
||||
TargetTicks);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Verification
|
||||
|
||||
```bash
|
||||
# Build must succeed
|
||||
dotnet build src\NT8.Adapters\NT8.Adapters.csproj --configuration Release
|
||||
|
||||
# All tests must still pass
|
||||
dotnet test NT8-SDK.sln --configuration Release --no-build
|
||||
```
|
||||
|
||||
**After deploy and recompile in NT8:**
|
||||
- [ ] Zero compile errors
|
||||
- [ ] "Simple ORB NT8" appears in strategy dropdown
|
||||
- [ ] "Minimal Test" appears in strategy dropdown
|
||||
|
||||
---
|
||||
|
||||
## 🚨 Constraints
|
||||
|
||||
- Surgical edit ONLY - one method, add null guard
|
||||
- C# 5.0 syntax - no modern features
|
||||
- Do NOT change any other logic
|
||||
- All 319 tests must still pass
|
||||
|
||||
---
|
||||
|
||||
## 📋 Git Commit
|
||||
|
||||
```bash
|
||||
git add src/NT8.Adapters/Strategies/SimpleORBNT8.cs
|
||||
git commit -m "fix: Guard Instrument null access in ConfigureStrategyParameters
|
||||
|
||||
Instrument.MasterInstrument is null when NT8 loads strategy list
|
||||
for dropdown. Added null guard to prevent runtime exception that
|
||||
silently removes strategy from available list."
|
||||
```
|
||||
|
||||
**READY FOR KILOCODE - CODE MODE** ✅
|
||||
83
docs/archive/fix-specs/NET_FRAMEWORK_CONVERSION.md
Normal file
83
docs/archive/fix-specs/NET_FRAMEWORK_CONVERSION.md
Normal file
@@ -0,0 +1,83 @@
|
||||
# NT8 SDK - .NET Framework 4.8 Compatibility Changes
|
||||
|
||||
## Summary
|
||||
Successfully converted the NT8 SDK from .NET Core 9 to .NET Framework 4.8 for NinjaTrader 8 compatibility.
|
||||
|
||||
## Key Changes Made
|
||||
|
||||
### 1. Framework Targeting
|
||||
- **Updated all projects** from `net9.0` to `net48`
|
||||
- **Disabled modern C# features** (nullable references, records, etc.)
|
||||
- **Set C# language version** to 5.0 for compatibility
|
||||
|
||||
### 2. Project Files Updated
|
||||
- `Directory.Build.props` - Framework targeting and compilation settings
|
||||
- All `.csproj` files - Target framework and package references
|
||||
- CI/CD pipeline - Windows runner for .NET Framework builds
|
||||
|
||||
### 3. Modern C# Feature Conversions
|
||||
- **Records → Classes**: Converted all `record` types to traditional classes
|
||||
- **Nullable references**: Removed `string?` syntax, using standard `string`
|
||||
- **String interpolation**: Converted to `String.Format()` calls
|
||||
- **Pattern matching**: Replaced with traditional `switch` statements
|
||||
|
||||
### 4. Package Dependencies
|
||||
- **Removed**: Microsoft.Extensions.Logging, Microsoft.Extensions.Configuration
|
||||
- **Added**: Newtonsoft.Json, System.ComponentModel.Annotations
|
||||
- **Testing**: Switched from xUnit to MSTest for .NET Framework compatibility
|
||||
|
||||
### 5. Custom Logging System
|
||||
- Created `ILogger` interface compatible with .NET Framework
|
||||
- Implemented `BasicLogger` class for console output
|
||||
- Maintains similar API to Microsoft.Extensions.Logging
|
||||
|
||||
### 6. File Structure
|
||||
- **Created**: Missing configuration models (`Configuration.cs`)
|
||||
- **Updated**: All interface implementations to use new models
|
||||
- **Converted**: Test files to MSTest framework
|
||||
- **Added**: Build verification script (`verify-build.bat`)
|
||||
|
||||
## What Works Now
|
||||
|
||||
### ✅ Compilation
|
||||
- All projects target .NET Framework 4.8
|
||||
- Compatible with NinjaTrader 8 requirements
|
||||
- No modern C# features that NT8 can't handle
|
||||
|
||||
### ✅ Core Functionality
|
||||
- Risk management system (BasicRiskManager)
|
||||
- Position sizing system (BasicPositionSizer)
|
||||
- Strategy interface framework
|
||||
- Configuration and logging systems
|
||||
|
||||
### ✅ Testing
|
||||
- MSTest framework compatible with .NET Framework
|
||||
- Basic test suite for risk management
|
||||
- Build verification script
|
||||
|
||||
## What's Missing (Phase 1)
|
||||
|
||||
### 🔄 NT8 Integration
|
||||
- Actual NinjaTrader 8 adapter implementations
|
||||
- Market data provider integration
|
||||
- Order execution system
|
||||
|
||||
### 🔄 Advanced Features
|
||||
- Full strategy examples
|
||||
- Configuration file handling
|
||||
- Enhanced logging and monitoring
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. **Test the build**: Run `verify-build.bat` to confirm compilation
|
||||
2. **NT8 Integration**: Begin Phase 1 with actual NT8 adapter development
|
||||
3. **Strategy Development**: Implement example strategies using the framework
|
||||
|
||||
## Compatibility Notes
|
||||
|
||||
- **NinjaTrader 8**: Requires .NET Framework 4.8 ✅
|
||||
- **C# Language**: Limited to C# 5.0 features ✅
|
||||
- **Package Management**: Uses NuGet packages compatible with .NET Framework ✅
|
||||
- **Testing**: MSTest framework works with Visual Studio and NT8 environment ✅
|
||||
|
||||
The SDK is now ready for NinjaTrader 8 integration while maintaining the sophisticated risk-first architecture from the original design.
|
||||
175
docs/archive/fix-specs/RTH_SESSION_FILTER_SPEC.md
Normal file
175
docs/archive/fix-specs/RTH_SESSION_FILTER_SPEC.md
Normal file
@@ -0,0 +1,175 @@
|
||||
# RTH Session Filter - Quick Fix Specification
|
||||
|
||||
**For:** Kilocode AI Agent
|
||||
**Priority:** URGENT
|
||||
**Mode:** Code Mode
|
||||
**Estimated Time:** 15-20 minutes
|
||||
**Files to Edit:** 1 file (NT8StrategyBase.cs)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Objective
|
||||
|
||||
Add session time filter to prevent trading during extended hours (ETH).
|
||||
Only allow trades during Regular Trading Hours (RTH): 9:30 AM - 4:00 PM ET.
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Fix: Add Session Filter to OnBarUpdate
|
||||
|
||||
**File:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`
|
||||
|
||||
**Find the OnBarUpdate method** (around line 150):
|
||||
|
||||
```csharp
|
||||
protected override void OnBarUpdate()
|
||||
{
|
||||
if (!_sdkInitialized || _sdkStrategy == null)
|
||||
{
|
||||
if (CurrentBar == 0)
|
||||
Print(string.Format("[SDK] Not initialized: sdkInit={0}, strategy={1}",
|
||||
_sdkInitialized, _sdkStrategy != null));
|
||||
return;
|
||||
}
|
||||
|
||||
if (CurrentBar < BarsRequiredToTrade)
|
||||
{
|
||||
if (CurrentBar == 0)
|
||||
Print(string.Format("[SDK] Waiting for bars: current={0}, required={1}",
|
||||
CurrentBar, BarsRequiredToTrade));
|
||||
return;
|
||||
}
|
||||
|
||||
if (Time[0] == _lastBarTime)
|
||||
return;
|
||||
```
|
||||
|
||||
**Add this session filter right after the BarsRequiredToTrade check:**
|
||||
|
||||
```csharp
|
||||
protected override void OnBarUpdate()
|
||||
{
|
||||
if (!_sdkInitialized || _sdkStrategy == null)
|
||||
{
|
||||
if (CurrentBar == 0)
|
||||
Print(string.Format("[SDK] Not initialized: sdkInit={0}, strategy={1}",
|
||||
_sdkInitialized, _sdkStrategy != null));
|
||||
return;
|
||||
}
|
||||
|
||||
if (CurrentBar < BarsRequiredToTrade)
|
||||
{
|
||||
if (CurrentBar == 0)
|
||||
Print(string.Format("[SDK] Waiting for bars: current={0}, required={1}",
|
||||
CurrentBar, BarsRequiredToTrade));
|
||||
return;
|
||||
}
|
||||
|
||||
// NEW: Session filter - only trade during RTH (9:30 AM - 4:00 PM ET)
|
||||
var currentTime = Time[0];
|
||||
var hour = currentTime.Hour;
|
||||
var minute = currentTime.Minute;
|
||||
|
||||
// Convert to minutes since midnight for easier comparison
|
||||
var currentMinutes = (hour * 60) + minute;
|
||||
var rthStart = (9 * 60) + 30; // 9:30 AM = 570 minutes
|
||||
var rthEnd = (16 * 60); // 4:00 PM = 960 minutes
|
||||
|
||||
if (currentMinutes < rthStart || currentMinutes >= rthEnd)
|
||||
{
|
||||
// Outside RTH - skip this bar
|
||||
if (CurrentBar == BarsRequiredToTrade)
|
||||
{
|
||||
Print(string.Format("[SDK] Outside RTH: {0:HH:mm} (RTH is 09:30-16:00)", currentTime));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (Time[0] == _lastBarTime)
|
||||
return;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Alternative: Add Property to Enable/Disable RTH Filter
|
||||
|
||||
If you want to make it configurable, add this property to the properties section:
|
||||
|
||||
```csharp
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "RTH Only", GroupName = "SDK", Order = 2)]
|
||||
public bool RthOnly { get; set; }
|
||||
```
|
||||
|
||||
Then in `State.SetDefaults`:
|
||||
|
||||
```csharp
|
||||
EnableSDK = true;
|
||||
RthOnly = true; // Default to RTH only
|
||||
```
|
||||
|
||||
And update the session filter:
|
||||
|
||||
```csharp
|
||||
// Session filter - only trade during RTH if enabled
|
||||
if (RthOnly)
|
||||
{
|
||||
var currentTime = Time[0];
|
||||
var hour = currentTime.Hour;
|
||||
var minute = currentTime.Minute;
|
||||
|
||||
var currentMinutes = (hour * 60) + minute;
|
||||
var rthStart = (9 * 60) + 30; // 9:30 AM
|
||||
var rthEnd = (16 * 60); // 4:00 PM
|
||||
|
||||
if (currentMinutes < rthStart || currentMinutes >= rthEnd)
|
||||
{
|
||||
if (CurrentBar == BarsRequiredToTrade)
|
||||
{
|
||||
Print(string.Format("[SDK] Outside RTH: {0:HH:mm} (RTH is 09:30-16:00)", currentTime));
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Verification
|
||||
|
||||
```bash
|
||||
# Build
|
||||
dotnet build src\NT8.Adapters\NT8.Adapters.csproj --configuration Release
|
||||
|
||||
# Deploy
|
||||
.\deployment\Deploy-To-NT8.ps1
|
||||
```
|
||||
|
||||
**In NT8 after recompile:**
|
||||
- Run backtest again
|
||||
- Check Output window
|
||||
- Should see: `[SDK] Outside RTH: 22:15 (RTH is 09:30-16:00)`
|
||||
- Should see intents ONLY during 9:30-16:00
|
||||
- Should see actual filled trades in results
|
||||
|
||||
---
|
||||
|
||||
## 📋 Git Commit
|
||||
|
||||
```bash
|
||||
git add src/NT8.Adapters/Strategies/NT8StrategyBase.cs
|
||||
git commit -m "fix: Add RTH session filter to prevent ETH trading
|
||||
|
||||
- Only trade during 9:30 AM - 4:00 PM ET
|
||||
- Add RthOnly property for configuration
|
||||
- Log when bars are outside RTH
|
||||
- Prevents order submission during extended hours
|
||||
|
||||
Fixes: Zero trades issue (was trading during ETH)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**READY FOR KILOCODE - CODE MODE** ✅
|
||||
|
||||
**Time: 15-20 minutes**
|
||||
150
docs/archive/fix-specs/STRATEGY_DROPDOWN_COMPLETE_FIX.md
Normal file
150
docs/archive/fix-specs/STRATEGY_DROPDOWN_COMPLETE_FIX.md
Normal file
@@ -0,0 +1,150 @@
|
||||
# NT8 Strategy Dropdown Complete Fix
|
||||
|
||||
**For:** Kilocode AI Agent
|
||||
**Priority:** URGENT
|
||||
**Mode:** Code Mode
|
||||
**Estimated Time:** 15-20 minutes
|
||||
**Files to Edit:** 2 files
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Objective
|
||||
|
||||
Fix two issues preventing SimpleORBNT8 from appearing in NT8 strategy dropdown:
|
||||
1. NT8StrategyBase (abstract) incorrectly appears in dropdown
|
||||
2. SimpleORBNT8 has runtime error preventing it from loading
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Fix 1: NT8StrategyBase.cs - Remove Name from abstract class
|
||||
|
||||
### File
|
||||
`src/NT8.Adapters/Strategies/NT8StrategyBase.cs`
|
||||
|
||||
### Problem
|
||||
Abstract base class sets `Name = "NT8 SDK Strategy Base"` which makes it
|
||||
appear in the strategy dropdown. Abstract strategies should NOT have a Name.
|
||||
|
||||
### Change: Remove or comment out Name assignment
|
||||
|
||||
**Find (around line 97):**
|
||||
```csharp
|
||||
protected override void OnStateChange()
|
||||
{
|
||||
if (State == State.SetDefaults)
|
||||
{
|
||||
Description = "SDK-integrated strategy base";
|
||||
Name = "NT8 SDK Strategy Base";
|
||||
Calculate = Calculate.OnBarClose;
|
||||
```
|
||||
|
||||
**Replace with:**
|
||||
```csharp
|
||||
protected override void OnStateChange()
|
||||
{
|
||||
if (State == State.SetDefaults)
|
||||
{
|
||||
Description = "SDK-integrated strategy base";
|
||||
// Name intentionally not set - this is an abstract base class
|
||||
Calculate = Calculate.OnBarClose;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Fix 2: SimpleORBNT8.cs - Guard Instrument null access
|
||||
|
||||
### File
|
||||
`src/NT8.Adapters/Strategies/SimpleORBNT8.cs`
|
||||
|
||||
### Problem
|
||||
`ConfigureStrategyParameters()` accesses `Instrument.MasterInstrument` which is
|
||||
null when NT8 loads the strategy for the dropdown list, causing a runtime
|
||||
exception that removes it from available strategies.
|
||||
|
||||
### Change: Add null guard
|
||||
|
||||
**Find:**
|
||||
```csharp
|
||||
protected override void ConfigureStrategyParameters()
|
||||
{
|
||||
_strategyConfig.RiskSettings.DailyLossLimit = DailyLossLimit;
|
||||
_strategyConfig.RiskSettings.MaxTradeRisk = MaxTradeRisk;
|
||||
_strategyConfig.RiskSettings.MaxOpenPositions = MaxOpenPositions;
|
||||
|
||||
var pointValue = Instrument.MasterInstrument.PointValue;
|
||||
var tickSize = Instrument.MasterInstrument.TickSize;
|
||||
var dollarRisk = StopTicks * tickSize * pointValue;
|
||||
|
||||
if (dollarRisk > _strategyConfig.RiskSettings.MaxTradeRisk)
|
||||
_strategyConfig.RiskSettings.MaxTradeRisk = dollarRisk;
|
||||
|
||||
_strategyConfig.SizingSettings.RiskPerTrade = RiskPerTrade;
|
||||
```
|
||||
|
||||
**Replace with:**
|
||||
```csharp
|
||||
protected override void ConfigureStrategyParameters()
|
||||
{
|
||||
_strategyConfig.RiskSettings.DailyLossLimit = DailyLossLimit;
|
||||
_strategyConfig.RiskSettings.MaxTradeRisk = MaxTradeRisk;
|
||||
_strategyConfig.RiskSettings.MaxOpenPositions = MaxOpenPositions;
|
||||
|
||||
// Guard: Instrument is null during strategy list loading
|
||||
if (Instrument != null && Instrument.MasterInstrument != null)
|
||||
{
|
||||
var pointValue = Instrument.MasterInstrument.PointValue;
|
||||
var tickSize = Instrument.MasterInstrument.TickSize;
|
||||
var dollarRisk = StopTicks * tickSize * pointValue;
|
||||
|
||||
if (dollarRisk > _strategyConfig.RiskSettings.MaxTradeRisk)
|
||||
_strategyConfig.RiskSettings.MaxTradeRisk = dollarRisk;
|
||||
}
|
||||
|
||||
_strategyConfig.SizingSettings.RiskPerTrade = RiskPerTrade;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Verification
|
||||
|
||||
```bash
|
||||
# Build must succeed
|
||||
dotnet build src\NT8.Adapters\NT8.Adapters.csproj --configuration Release
|
||||
|
||||
# Redeploy
|
||||
.\deployment\Deploy-To-NT8.ps1
|
||||
```
|
||||
|
||||
**In NT8 after recompile:**
|
||||
- [ ] "NT8 SDK Strategy Base" NO LONGER appears in dropdown
|
||||
- [ ] "Simple ORB NT8" DOES appear in dropdown
|
||||
- [ ] "Minimal Test" still appears (if compiled)
|
||||
|
||||
---
|
||||
|
||||
## 🚨 Constraints
|
||||
|
||||
- Two surgical edits only
|
||||
- C# 5.0 syntax
|
||||
- Do NOT change other logic
|
||||
- All tests must pass
|
||||
|
||||
---
|
||||
|
||||
## 📋 Git Commit
|
||||
|
||||
```bash
|
||||
git add src/NT8.Adapters/Strategies/NT8StrategyBase.cs
|
||||
git add src/NT8.Adapters/Strategies/SimpleORBNT8.cs
|
||||
git commit -m "fix: Make abstract base invisible, guard Instrument access
|
||||
|
||||
- Remove Name from NT8StrategyBase (abstract shouldn't appear in dropdown)
|
||||
- Add null guard for Instrument access in ConfigureStrategyParameters
|
||||
- Prevents runtime error when NT8 loads strategy list
|
||||
|
||||
Fixes: SimpleORBNT8 now appears in strategy dropdown"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**READY FOR KILOCODE - CODE MODE** ✅
|
||||
@@ -0,0 +1,260 @@
|
||||
# NT8 Integration - Complete Specification Package
|
||||
|
||||
**Created:** February 17, 2026
|
||||
**Status:** ✅ All Phases Specified, Ready for Execution
|
||||
**Total Estimated Time:** 12-16 hours (3 phases)
|
||||
|
||||
---
|
||||
|
||||
## 📦 Specification Documents Created
|
||||
|
||||
### Phase A: Foundation (4-5 hours)
|
||||
**File:** `PHASE_A_SPECIFICATION.md`
|
||||
**Status:** ✅ Complete
|
||||
|
||||
**Deliverables:**
|
||||
- NT8DataConverterTests.cs (27 tests)
|
||||
- NT8ExecutionAdapter.cs (order tracking & NT8 integration)
|
||||
- NT8ExecutionAdapterTests.cs (15 tests)
|
||||
|
||||
**What It Does:**
|
||||
- Tests existing data conversion logic
|
||||
- Creates execution adapter for order submission
|
||||
- Validates thread-safe order tracking
|
||||
- Maps NT8 callbacks to SDK state
|
||||
|
||||
---
|
||||
|
||||
### Phase B: Strategy Integration (4-5 hours)
|
||||
**File:** `PHASE_B_SPECIFICATION.md`
|
||||
**Status:** ✅ Complete
|
||||
|
||||
**Deliverables:**
|
||||
- NT8StrategyBase.cs (~800-1000 lines)
|
||||
- SimpleORBNT8.cs (~150-200 lines)
|
||||
- MinimalTestStrategy.cs (~50 lines)
|
||||
|
||||
**What It Does:**
|
||||
- Inherits from NinjaTrader Strategy class
|
||||
- Implements NT8 lifecycle (OnStateChange, OnBarUpdate)
|
||||
- Bridges NT8 events to SDK components
|
||||
- Submits orders to NT8 platform
|
||||
- Handles order/execution callbacks
|
||||
|
||||
---
|
||||
|
||||
### Phase C: Deployment & Testing (3-4 hours)
|
||||
**File:** `PHASE_C_SPECIFICATION.md`
|
||||
**Status:** ✅ Complete
|
||||
|
||||
**Deliverables:**
|
||||
- Deploy-To-NT8.ps1 (~300 lines)
|
||||
- Verify-Deployment.ps1 (~100 lines)
|
||||
- NT8IntegrationTests.cs (~500 lines, 15+ tests)
|
||||
|
||||
**What It Does:**
|
||||
- Automates complete deployment process
|
||||
- Verifies deployment status
|
||||
- End-to-end integration tests
|
||||
- Performance validation (<200ms)
|
||||
- Thread safety validation
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Complete Project Flow
|
||||
|
||||
```
|
||||
Phase A (Foundation)
|
||||
↓
|
||||
Phase B (Strategy Integration)
|
||||
↓
|
||||
Phase C (Deployment & Testing)
|
||||
↓
|
||||
READY FOR NT8 LIVE TESTING
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📋 Execution Instructions for Kilocode
|
||||
|
||||
### Phase A
|
||||
```
|
||||
1. Read: PHASE_A_SPECIFICATION.md
|
||||
2. Mode: Code Mode
|
||||
3. Time: 4-5 hours
|
||||
4. Deliverables: 3 files, 42 tests
|
||||
5. Success: All tests pass, >90% coverage
|
||||
```
|
||||
|
||||
### Phase B (Start after Phase A complete)
|
||||
```
|
||||
1. Read: PHASE_B_SPECIFICATION.md
|
||||
2. Mode: Code Mode
|
||||
3. Time: 4-5 hours
|
||||
4. Deliverables: 3 strategy files
|
||||
5. Success: Compiles in NT8, runs without errors
|
||||
```
|
||||
|
||||
### Phase C (Start after Phase B complete)
|
||||
```
|
||||
1. Read: PHASE_C_SPECIFICATION.md
|
||||
2. Mode: Code Mode
|
||||
3. Time: 3-4 hours
|
||||
4. Deliverables: 2 scripts, 15+ tests
|
||||
5. Success: Automated deployment works, all tests pass
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Complete Success Criteria
|
||||
|
||||
### Phase A Complete When:
|
||||
- [ ] 27 NT8DataConverter tests passing
|
||||
- [ ] NT8ExecutionAdapter implemented
|
||||
- [ ] 15 ExecutionAdapter tests passing
|
||||
- [ ] All 42 tests passing
|
||||
- [ ] >90% code coverage
|
||||
- [ ] Thread safety verified
|
||||
- [ ] Committed to Git
|
||||
|
||||
### Phase B Complete When:
|
||||
- [ ] All 3 strategy files created
|
||||
- [ ] Compiles in NT8 with zero errors
|
||||
- [ ] MinimalTestStrategy runs
|
||||
- [ ] SimpleORBNT8 initializes SDK
|
||||
- [ ] SimpleORBNT8 generates trading intents
|
||||
- [ ] SimpleORBNT8 submits orders
|
||||
- [ ] Runs 1+ hours without errors
|
||||
- [ ] Committed to Git
|
||||
|
||||
### Phase C Complete When:
|
||||
- [ ] Deploy-To-NT8.ps1 works
|
||||
- [ ] Verify-Deployment.ps1 validates
|
||||
- [ ] 15+ integration tests passing
|
||||
- [ ] Performance <200ms
|
||||
- [ ] Thread safety with 100 concurrent orders
|
||||
- [ ] End-to-end workflow validated
|
||||
- [ ] Committed to Git
|
||||
|
||||
---
|
||||
|
||||
## 🎯 After All Phases Complete
|
||||
|
||||
### What You'll Have:
|
||||
1. ✅ Complete NT8 integration layer
|
||||
2. ✅ 240+ unit tests + 15+ integration tests
|
||||
3. ✅ Automated deployment tooling
|
||||
4. ✅ Performance validated (<200ms)
|
||||
5. ✅ Thread safety verified
|
||||
6. ✅ Ready for NT8 simulation testing
|
||||
|
||||
### Next Steps (Manual):
|
||||
1. Deploy to NT8 using script
|
||||
2. Compile in NinjaScript Editor
|
||||
3. Test MinimalTestStrategy on chart
|
||||
4. Test SimpleORBNT8 on simulation
|
||||
5. Run 24-hour simulation test
|
||||
6. Validate risk controls
|
||||
7. Move to production (gradually)
|
||||
|
||||
---
|
||||
|
||||
## 📊 Summary Statistics
|
||||
|
||||
**Total Deliverables:**
|
||||
- Source Files: 6 (3 adapters, 3 strategies)
|
||||
- Test Files: 3
|
||||
- Scripts: 2
|
||||
- Total Lines of Code: ~3,500-4,000
|
||||
- Total Tests: 57+ (42 Phase A, 15+ Phase C)
|
||||
|
||||
**Total Time:**
|
||||
- Phase A: 4-5 hours
|
||||
- Phase B: 4-5 hours
|
||||
- Phase C: 3-4 hours
|
||||
- **Total: 11-14 hours**
|
||||
|
||||
**Quality Metrics:**
|
||||
- Code coverage: >90%
|
||||
- Performance: <200ms
|
||||
- Thread safety: 100 concurrent orders
|
||||
- Zero warnings: Yes
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Kilocode Execution Plan
|
||||
|
||||
### Week 1: Phase A (Monday-Tuesday)
|
||||
- Monday morning: Start Phase A
|
||||
- Monday afternoon: Complete Phase A
|
||||
- Monday evening: Verify & commit
|
||||
- Tuesday: Buffer for issues
|
||||
|
||||
### Week 1: Phase B (Wednesday-Thursday)
|
||||
- Wednesday morning: Start Phase B
|
||||
- Wednesday afternoon: Complete Phase B
|
||||
- Wednesday evening: Test in NT8
|
||||
- Thursday: Debugging & refinement
|
||||
|
||||
### Week 1: Phase C (Friday)
|
||||
- Friday morning: Start Phase C
|
||||
- Friday afternoon: Complete Phase C
|
||||
- Friday evening: Full integration test
|
||||
|
||||
### Week 2: Validation
|
||||
- Monday-Friday: NT8 simulation testing
|
||||
- Document issues
|
||||
- Refine as needed
|
||||
- Prepare for production
|
||||
|
||||
---
|
||||
|
||||
## 📚 Reference Documents
|
||||
|
||||
**Architecture:**
|
||||
- `ARCHITECTURE.md` - System design
|
||||
- `API_REFERENCE.md` - API documentation
|
||||
- `NT8_INTEGRATION_IMPLEMENTATION_PLAN.md` - High-level plan
|
||||
|
||||
**Specifications:**
|
||||
- `PHASE_A_SPECIFICATION.md` - Foundation (THIS)
|
||||
- `PHASE_B_SPECIFICATION.md` - Strategy integration
|
||||
- `PHASE_C_SPECIFICATION.md` - Deployment & testing
|
||||
|
||||
**Project Context:**
|
||||
- `PROJECT_HANDOVER.md` - Overall project status
|
||||
- `NEXT_STEPS_RECOMMENDED.md` - Post-integration roadmap
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Current Status
|
||||
|
||||
**Phase 5 (Analytics):** ✅ Complete (240+ tests passing)
|
||||
**Phase A (NT8 Foundation):** 📝 Specification complete, ready for Kilocode
|
||||
**Phase B (Strategy Integration):** 📝 Specification complete, waiting for Phase A
|
||||
**Phase C (Deployment):** 📝 Specification complete, waiting for Phase B
|
||||
|
||||
**Overall Project:** ~85% complete
|
||||
**After NT8 Integration:** ~95% complete
|
||||
**Remaining:** Production hardening, live deployment
|
||||
|
||||
---
|
||||
|
||||
## ✅ Ready for Handoff to Kilocode
|
||||
|
||||
All three phases are fully specified with:
|
||||
- ✅ Complete technical requirements
|
||||
- ✅ Detailed code specifications
|
||||
- ✅ Comprehensive test requirements
|
||||
- ✅ Success criteria defined
|
||||
- ✅ Constraints documented
|
||||
- ✅ Step-by-step workflows
|
||||
- ✅ Git commit templates
|
||||
|
||||
**Kilocode can now execute all three phases autonomously with minimal supervision.**
|
||||
|
||||
---
|
||||
|
||||
**Total Documentation Created:** 4 specification files, ~5,000 lines of detailed specs
|
||||
|
||||
**Ready to begin Phase A!** 🚀
|
||||
@@ -0,0 +1,745 @@
|
||||
# NinjaTrader 8 Integration - Complete Implementation Plan
|
||||
|
||||
**Project:** NT8 SDK
|
||||
**Phase:** NT8 Integration Layer
|
||||
**Date:** February 17, 2026
|
||||
**Status:** Planning → Implementation Ready
|
||||
**Estimated Time:** 12-16 hours total
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Objective
|
||||
|
||||
Build a **complete, production-ready NinjaTrader 8 integration layer** that enables the NT8 SDK to run strategies inside NinjaTrader 8 with full order execution, risk management, and performance tracking.
|
||||
|
||||
**Success Criteria:**
|
||||
- ✅ SimpleORB strategy compiles in NinjaTrader 8
|
||||
- ✅ Strategy can be enabled on a chart
|
||||
- ✅ Orders submit correctly to simulation account
|
||||
- ✅ Risk controls trigger appropriately
|
||||
- ✅ All 240+ existing tests still pass
|
||||
- ✅ Zero compilation warnings in NT8
|
||||
- ✅ Strategy runs for 1+ hours without errors
|
||||
|
||||
---
|
||||
|
||||
## 📋 Current State Assessment
|
||||
|
||||
### What We Have ✅
|
||||
- **Core SDK:** 20,000 lines of production code (Phases 0-5 complete)
|
||||
- **Strategy Logic:** SimpleORBStrategy fully implemented
|
||||
- **Risk System:** Multi-tier validation operational
|
||||
- **Position Sizing:** Multiple sizing methods working
|
||||
- **Analytics:** Complete performance tracking
|
||||
- **Test Coverage:** 240+ tests passing (100% pass rate)
|
||||
|
||||
### What's Missing ❌
|
||||
1. **NT8 Strategy Base Class** - Inherits from NinjaTrader's Strategy class
|
||||
2. **Real Order Adapter** - Actual NT8 order submission (not stubs)
|
||||
3. **Data Adapter** - NT8 bar/market data conversion
|
||||
4. **Execution Adapter** - Fill/update callback handling
|
||||
5. **Deployment Automation** - Script to copy files to NT8
|
||||
6. **Minimal Test Strategy** - Simple validation strategy
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Implementation Architecture
|
||||
|
||||
### Layer Separation Strategy
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ NinjaTrader 8 Platform │
|
||||
│ (Strategy base class, Order objects, Instrument, etc.) │
|
||||
└────────────────────┬────────────────────────────────────────┘
|
||||
│
|
||||
↓ Inherits & Implements
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ NT8StrategyBase (NEW) │
|
||||
│ • Inherits: NinjaTrader.NinjaScript.Strategies.Strategy │
|
||||
│ • Implements: NT8 lifecycle (OnStateChange, OnBarUpdate) │
|
||||
│ • Bridges: NT8 events → SDK components │
|
||||
│ • Location: Deployed directly to NT8 (not in DLL) │
|
||||
└────────────────────┬────────────────────────────────────────┘
|
||||
│
|
||||
↓ Uses
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ NT8ExecutionAdapter (NEW) │
|
||||
│ • Order submission: SDK OrderRequest → NT8 EnterLong/Short │
|
||||
│ • Order management: NT8 Order tracking │
|
||||
│ • Fill handling: NT8 Execution → SDK OrderStatus │
|
||||
│ • Location: NT8.Adapters.dll │
|
||||
└────────────────────┬────────────────────────────────────────┘
|
||||
│
|
||||
↓ Coordinates
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ NT8.Core.dll │
|
||||
│ • All SDK business logic (already complete) │
|
||||
│ • Risk, Sizing, OMS, Analytics, Intelligence │
|
||||
│ • Location: NT8 Custom\bin folder │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Why This Architecture?
|
||||
|
||||
1. **NT8StrategyBase deployed as .cs file** - NT8 must compile it to access platform APIs
|
||||
2. **NT8ExecutionAdapter in DLL** - Reusable adapter logic, testable
|
||||
3. **Core SDK in DLL** - All business logic stays in tested, versioned SDK
|
||||
|
||||
---
|
||||
|
||||
## 📦 Deliverables (6 Major Components)
|
||||
|
||||
### Component 1: NT8ExecutionAdapter.cs
|
||||
**Location:** `src/NT8.Adapters/NinjaTrader/NT8ExecutionAdapter.cs`
|
||||
**Purpose:** Bridge between SDK OrderRequest and NT8 Order objects
|
||||
**Time:** 3-4 hours
|
||||
|
||||
**Key Responsibilities:**
|
||||
- Accept SDK `OrderRequest`, create NT8 `Order` objects
|
||||
- Submit orders via NT8 `EnterLong()`, `EnterShort()`, `ExitLong()`, `ExitShort()`
|
||||
- Track NT8 orders and map to SDK order IDs
|
||||
- Handle NT8 `OnOrderUpdate()` callbacks
|
||||
- Handle NT8 `OnExecutionUpdate()` callbacks
|
||||
- Thread-safe order state management
|
||||
|
||||
**Interface:**
|
||||
```csharp
|
||||
public class NT8ExecutionAdapter
|
||||
{
|
||||
// Submit order to NT8
|
||||
public string SubmitOrder(
|
||||
NinjaTrader.NinjaScript.Strategies.Strategy strategy,
|
||||
OrderRequest request);
|
||||
|
||||
// Cancel order in NT8
|
||||
public bool CancelOrder(
|
||||
NinjaTrader.NinjaScript.Strategies.Strategy strategy,
|
||||
string orderId);
|
||||
|
||||
// Process NT8 order update
|
||||
public void ProcessOrderUpdate(
|
||||
NinjaTrader.Cbi.Order order,
|
||||
double limitPrice,
|
||||
double stopPrice,
|
||||
int quantity,
|
||||
int filled,
|
||||
double averageFillPrice,
|
||||
NinjaTrader.Cbi.OrderState orderState,
|
||||
DateTime time,
|
||||
NinjaTrader.Cbi.ErrorCode errorCode,
|
||||
string nativeError);
|
||||
|
||||
// Process NT8 execution
|
||||
public void ProcessExecution(
|
||||
NinjaTrader.Cbi.Execution execution);
|
||||
|
||||
// Get order status
|
||||
public OrderStatus GetOrderStatus(string orderId);
|
||||
}
|
||||
```
|
||||
|
||||
**Dependencies:**
|
||||
- Requires reference to `NinjaTrader.Core.dll`
|
||||
- Requires reference to `NinjaTrader.Cbi.dll`
|
||||
- Uses SDK `OrderRequest`, `OrderStatus`, `OrderState`
|
||||
|
||||
---
|
||||
|
||||
### Component 2: NT8DataAdapter.cs
|
||||
**Location:** `src/NT8.Adapters/NinjaTrader/NT8DataAdapter.cs`
|
||||
**Purpose:** Convert NT8 market data to SDK format
|
||||
**Time:** 2 hours
|
||||
|
||||
**Key Responsibilities:**
|
||||
- Convert NT8 bars to SDK `BarData`
|
||||
- Convert NT8 account info to SDK `AccountInfo`
|
||||
- Convert NT8 position to SDK `Position`
|
||||
- Convert NT8 instrument to SDK `Instrument`
|
||||
|
||||
**Interface:**
|
||||
```csharp
|
||||
public class NT8DataAdapter
|
||||
{
|
||||
// Convert NT8 bar to SDK format
|
||||
public static BarData ConvertBar(
|
||||
NinjaTrader.Data.Bars bars,
|
||||
int barsAgo);
|
||||
|
||||
// Convert NT8 account to SDK format
|
||||
public static AccountInfo ConvertAccount(
|
||||
NinjaTrader.Cbi.Account account);
|
||||
|
||||
// Convert NT8 position to SDK format
|
||||
public static Position ConvertPosition(
|
||||
NinjaTrader.Cbi.Position position);
|
||||
|
||||
// Build strategy context
|
||||
public static StrategyContext BuildContext(
|
||||
NinjaTrader.NinjaScript.Strategies.Strategy strategy,
|
||||
AccountInfo account,
|
||||
Position position);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Component 3: NT8StrategyBase.cs
|
||||
**Location:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`
|
||||
**Purpose:** Base class for all NT8-integrated strategies
|
||||
**Time:** 4-5 hours
|
||||
**Deployment:** Copied to NT8 as .cs file (not compiled into DLL)
|
||||
|
||||
**Key Responsibilities:**
|
||||
- Inherit from `NinjaTrader.NinjaScript.Strategies.Strategy`
|
||||
- Implement NT8 lifecycle methods
|
||||
- Create and manage SDK components
|
||||
- Bridge NT8 events to SDK
|
||||
- Handle errors and logging
|
||||
|
||||
**Lifecycle Implementation:**
|
||||
```csharp
|
||||
public abstract class NT8StrategyBase
|
||||
: NinjaTrader.NinjaScript.Strategies.Strategy
|
||||
{
|
||||
protected IStrategy _sdkStrategy;
|
||||
protected IRiskManager _riskManager;
|
||||
protected IPositionSizer _positionSizer;
|
||||
protected NT8ExecutionAdapter _executionAdapter;
|
||||
protected ILogger _logger;
|
||||
|
||||
protected override void OnStateChange()
|
||||
{
|
||||
switch (State)
|
||||
{
|
||||
case State.SetDefaults:
|
||||
// Set strategy defaults
|
||||
break;
|
||||
|
||||
case State.Configure:
|
||||
// Add data series, indicators
|
||||
break;
|
||||
|
||||
case State.DataLoaded:
|
||||
// Initialize SDK components
|
||||
InitializeSdkComponents();
|
||||
break;
|
||||
|
||||
case State.Historical:
|
||||
case State.Transition:
|
||||
case State.Realtime:
|
||||
// Strategy ready for trading
|
||||
break;
|
||||
|
||||
case State.Terminated:
|
||||
// Cleanup
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnBarUpdate()
|
||||
{
|
||||
if (CurrentBar < BarsRequiredToTrade) return;
|
||||
|
||||
// Convert NT8 bar to SDK
|
||||
var barData = NT8DataAdapter.ConvertBar(Bars, 0);
|
||||
var context = NT8DataAdapter.BuildContext(this, account, position);
|
||||
|
||||
// Call SDK strategy
|
||||
var intent = _sdkStrategy.OnBar(barData, context);
|
||||
|
||||
if (intent != null)
|
||||
{
|
||||
ProcessIntent(intent, context);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnOrderUpdate(
|
||||
Order order, double limitPrice, double stopPrice,
|
||||
int quantity, int filled, double averageFillPrice,
|
||||
OrderState orderState, DateTime time,
|
||||
ErrorCode errorCode, string nativeError)
|
||||
{
|
||||
_executionAdapter.ProcessOrderUpdate(
|
||||
order, limitPrice, stopPrice, quantity, filled,
|
||||
averageFillPrice, orderState, time, errorCode, nativeError);
|
||||
}
|
||||
|
||||
protected override void OnExecutionUpdate(
|
||||
Execution execution, string executionId,
|
||||
double price, int quantity,
|
||||
MarketPosition marketPosition, string orderId,
|
||||
DateTime time)
|
||||
{
|
||||
_executionAdapter.ProcessExecution(execution);
|
||||
}
|
||||
|
||||
// Abstract methods for derived strategies
|
||||
protected abstract IStrategy CreateSdkStrategy();
|
||||
protected abstract void ConfigureStrategyParameters();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Component 4: SimpleORBNT8.cs
|
||||
**Location:** `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`
|
||||
**Purpose:** Concrete SimpleORB implementation for NT8
|
||||
**Time:** 1-2 hours
|
||||
**Deployment:** Copied to NT8 as .cs file
|
||||
|
||||
**Implementation:**
|
||||
```csharp
|
||||
public class SimpleORBNT8 : NT8StrategyBase
|
||||
{
|
||||
#region User-Configurable Parameters
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Opening Range Minutes", GroupName = "Strategy")]
|
||||
public int OpeningRangeMinutes { get; set; }
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Std Dev Multiplier", GroupName = "Strategy")]
|
||||
public double StdDevMultiplier { get; set; }
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Stop Ticks", GroupName = "Risk")]
|
||||
public int StopTicks { get; set; }
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Target Ticks", GroupName = "Risk")]
|
||||
public int TargetTicks { get; set; }
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Daily Loss Limit", GroupName = "Risk")]
|
||||
public double DailyLossLimit { get; set; }
|
||||
|
||||
#endregion
|
||||
|
||||
protected override void OnStateChange()
|
||||
{
|
||||
if (State == State.SetDefaults)
|
||||
{
|
||||
Name = "Simple ORB NT8";
|
||||
Description = "Opening Range Breakout with SDK integration";
|
||||
Calculate = Calculate.OnBarClose;
|
||||
|
||||
// Default parameters
|
||||
OpeningRangeMinutes = 30;
|
||||
StdDevMultiplier = 1.0;
|
||||
StopTicks = 8;
|
||||
TargetTicks = 16;
|
||||
DailyLossLimit = 1000.0;
|
||||
}
|
||||
|
||||
base.OnStateChange();
|
||||
}
|
||||
|
||||
protected override IStrategy CreateSdkStrategy()
|
||||
{
|
||||
return new NT8.Strategies.Examples.SimpleORBStrategy(
|
||||
OpeningRangeMinutes,
|
||||
StdDevMultiplier);
|
||||
}
|
||||
|
||||
protected override void ConfigureStrategyParameters()
|
||||
{
|
||||
_strategyConfig.RiskSettings.DailyLossLimit = DailyLossLimit;
|
||||
_strategyConfig.RiskSettings.MaxTradeRisk = StopTicks * Instrument.MasterInstrument.PointValue;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Component 5: MinimalTestStrategy.cs
|
||||
**Location:** `src/NT8.Adapters/Strategies/MinimalTestStrategy.cs`
|
||||
**Purpose:** Simple test strategy to validate integration
|
||||
**Time:** 30 minutes
|
||||
|
||||
**Implementation:**
|
||||
```csharp
|
||||
public class MinimalTestStrategy
|
||||
: NinjaTrader.NinjaScript.Strategies.Strategy
|
||||
{
|
||||
protected override void OnStateChange()
|
||||
{
|
||||
if (State == State.SetDefaults)
|
||||
{
|
||||
Name = "Minimal Test";
|
||||
Description = "Validates NT8 integration without SDK";
|
||||
Calculate = Calculate.OnBarClose;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnBarUpdate()
|
||||
{
|
||||
if (CurrentBar < 20) return;
|
||||
|
||||
// Just log, no trading
|
||||
Print(string.Format("{0}: O={1:F2} H={2:F2} L={3:F2} C={4:F2} V={5}",
|
||||
Time[0].ToString("HH:mm:ss"),
|
||||
Open[0], High[0], Low[0], Close[0], Volume[0]));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Component 6: Deploy-To-NT8.ps1
|
||||
**Location:** `deployment/Deploy-To-NT8.ps1`
|
||||
**Purpose:** Automate deployment to NinjaTrader 8
|
||||
**Time:** 1 hour
|
||||
|
||||
**Script:**
|
||||
```powershell
|
||||
# NT8 SDK Deployment Script
|
||||
param(
|
||||
[switch]$BuildFirst = $true,
|
||||
[switch]$RunTests = $true,
|
||||
[switch]$CopyStrategies = $true
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$sdkRoot = "C:\dev\nt8-sdk"
|
||||
$nt8Custom = "$env:USERPROFILE\Documents\NinjaTrader 8\bin\Custom"
|
||||
$nt8Strategies = "$nt8Custom\Strategies"
|
||||
|
||||
Write-Host "NT8 SDK Deployment Script" -ForegroundColor Cyan
|
||||
Write-Host "=" * 60
|
||||
|
||||
# Step 1: Build
|
||||
if ($BuildFirst) {
|
||||
Write-Host "`n[1/5] Building SDK..." -ForegroundColor Yellow
|
||||
|
||||
Push-Location $sdkRoot
|
||||
dotnet clean --configuration Release | Out-Null
|
||||
$buildResult = dotnet build --configuration Release
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host "Build FAILED!" -ForegroundColor Red
|
||||
Pop-Location
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "Build succeeded" -ForegroundColor Green
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
# Step 2: Run Tests
|
||||
if ($RunTests) {
|
||||
Write-Host "`n[2/5] Running tests..." -ForegroundColor Yellow
|
||||
|
||||
Push-Location $sdkRoot
|
||||
$testResult = dotnet test --configuration Release --no-build
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host "Tests FAILED!" -ForegroundColor Red
|
||||
Pop-Location
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "All tests passed" -ForegroundColor Green
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
# Step 3: Copy Core DLL
|
||||
Write-Host "`n[3/5] Copying SDK DLLs..." -ForegroundColor Yellow
|
||||
|
||||
$coreDll = "$sdkRoot\src\NT8.Core\bin\Release\net48\NT8.Core.dll"
|
||||
$corePdb = "$sdkRoot\src\NT8.Core\bin\Release\net48\NT8.Core.pdb"
|
||||
|
||||
Copy-Item $coreDll $nt8Custom -Force
|
||||
Copy-Item $corePdb $nt8Custom -Force
|
||||
|
||||
Write-Host "Copied NT8.Core.dll and .pdb" -ForegroundColor Green
|
||||
|
||||
# Step 4: Copy Dependencies
|
||||
Write-Host "`n[4/5] Copying dependencies..." -ForegroundColor Yellow
|
||||
|
||||
$depsPath = "$sdkRoot\src\NT8.Core\bin\Release\net48"
|
||||
$deps = @(
|
||||
"Microsoft.Extensions.*.dll",
|
||||
"System.Memory.dll",
|
||||
"System.Buffers.dll"
|
||||
)
|
||||
|
||||
foreach ($dep in $deps) {
|
||||
Get-ChildItem "$depsPath\$dep" -ErrorAction SilentlyContinue |
|
||||
Copy-Item -Destination $nt8Custom -Force
|
||||
}
|
||||
|
||||
Write-Host "Copied dependencies" -ForegroundColor Green
|
||||
|
||||
# Step 5: Copy Strategies
|
||||
if ($CopyStrategies) {
|
||||
Write-Host "`n[5/5] Copying strategies..." -ForegroundColor Yellow
|
||||
|
||||
$strategyFiles = @(
|
||||
"$sdkRoot\src\NT8.Adapters\Strategies\NT8StrategyBase.cs",
|
||||
"$sdkRoot\src\NT8.Adapters\Strategies\SimpleORBNT8.cs",
|
||||
"$sdkRoot\src\NT8.Adapters\Strategies\MinimalTestStrategy.cs"
|
||||
)
|
||||
|
||||
foreach ($file in $strategyFiles) {
|
||||
if (Test-Path $file) {
|
||||
Copy-Item $file $nt8Strategies -Force
|
||||
Write-Host " Copied $(Split-Path $file -Leaf)" -ForegroundColor Green
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "`n" + ("=" * 60) -ForegroundColor Cyan
|
||||
Write-Host "Deployment Complete!" -ForegroundColor Green
|
||||
Write-Host "`nNext steps:" -ForegroundColor Yellow
|
||||
Write-Host "1. Open NinjaTrader 8"
|
||||
Write-Host "2. Tools -> NinjaScript Editor (F5)"
|
||||
Write-Host "3. Compile -> Compile All (F5)"
|
||||
Write-Host "4. Verify compilation succeeds"
|
||||
Write-Host "5. Create new strategy instance on chart"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Implementation Sequence
|
||||
|
||||
### Phase A: Foundation (4-5 hours)
|
||||
**Goal:** Build adapter infrastructure
|
||||
|
||||
1. **Create NT8DataAdapter.cs** (2 hours)
|
||||
- Implement bar conversion
|
||||
- Implement account conversion
|
||||
- Implement position conversion
|
||||
- Implement context builder
|
||||
- Write unit tests (20+ tests)
|
||||
|
||||
2. **Create NT8ExecutionAdapter.cs** (2-3 hours)
|
||||
- Implement order submission logic
|
||||
- Implement order state tracking
|
||||
- Implement callback processing
|
||||
- Write unit tests (30+ tests)
|
||||
|
||||
**Verification:**
|
||||
```bash
|
||||
dotnet test --filter "FullyQualifiedName~NT8DataAdapter"
|
||||
dotnet test --filter "FullyQualifiedName~NT8ExecutionAdapter"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Phase B: Strategy Base (4-5 hours)
|
||||
**Goal:** Build NT8 strategy base class
|
||||
|
||||
3. **Create NT8StrategyBase.cs** (3-4 hours)
|
||||
- Implement state change lifecycle
|
||||
- Implement OnBarUpdate integration
|
||||
- Implement order callback handling
|
||||
- Add error handling and logging
|
||||
- Add component initialization
|
||||
|
||||
4. **Create SimpleORBNT8.cs** (1 hour)
|
||||
- Implement concrete strategy
|
||||
- Add NT8 property decorators
|
||||
- Configure strategy parameters
|
||||
|
||||
**Manual Verification:**
|
||||
- Copy to NT8 Strategies folder
|
||||
- Open NinjaScript Editor
|
||||
- Verify no compilation errors
|
||||
|
||||
---
|
||||
|
||||
### Phase C: Testing & Deployment (3-4 hours)
|
||||
**Goal:** Validate and deploy
|
||||
|
||||
5. **Create MinimalTestStrategy.cs** (30 min)
|
||||
- Simple logging strategy
|
||||
- No SDK dependencies
|
||||
- Validates NT8 integration basics
|
||||
|
||||
6. **Create Deploy-To-NT8.ps1** (1 hour)
|
||||
- Automate build
|
||||
- Automate file copying
|
||||
- Add verification steps
|
||||
|
||||
7. **Integration Testing** (2-3 hours)
|
||||
- Deploy to NT8
|
||||
- Compile in NT8
|
||||
- Enable MinimalTestStrategy on chart (verify basic NT8 integration)
|
||||
- Enable SimpleORBNT8 on chart (verify full SDK integration)
|
||||
- Run on sim data for 1 hour
|
||||
- Verify risk controls
|
||||
- Verify order submission
|
||||
- Document any issues
|
||||
|
||||
---
|
||||
|
||||
## ✅ Verification Checklist
|
||||
|
||||
### Build Verification
|
||||
- [ ] `dotnet build --configuration Release` succeeds
|
||||
- [ ] `dotnet test --configuration Release` all 240+ tests pass
|
||||
- [ ] Zero build warnings for new adapter code
|
||||
- [ ] NT8.Core.dll builds successfully
|
||||
- [ ] Dependencies copy correctly
|
||||
|
||||
### NT8 Compilation Verification
|
||||
- [ ] NinjaScript Editor opens without errors
|
||||
- [ ] "Compile All" succeeds with zero errors
|
||||
- [ ] Zero warnings for NT8StrategyBase.cs
|
||||
- [ ] Zero warnings for SimpleORBNT8.cs
|
||||
- [ ] MinimalTestStrategy.cs compiles
|
||||
- [ ] All strategies visible in strategy dropdown
|
||||
|
||||
### Runtime Verification (Simulation)
|
||||
- [ ] MinimalTestStrategy enables on chart without errors
|
||||
- [ ] MinimalTestStrategy logs bars correctly
|
||||
- [ ] SimpleORBNT8 enables on chart without errors
|
||||
- [ ] SimpleORBNT8 initializes SDK components
|
||||
- [ ] Opening range calculated correctly
|
||||
- [ ] Risk validation triggers
|
||||
- [ ] Orders submit to simulation account
|
||||
- [ ] Fills process correctly
|
||||
- [ ] Stops and targets placed correctly
|
||||
- [ ] Strategy runs for 1+ hours without errors
|
||||
- [ ] Daily loss limit triggers correctly
|
||||
- [ ] Emergency flatten works
|
||||
|
||||
### Performance Verification
|
||||
- [ ] OnBarUpdate executes in <200ms
|
||||
- [ ] Order submission in <5ms (excluding NT8)
|
||||
- [ ] No memory leaks over 1+ hour run
|
||||
- [ ] Thread-safe operation confirmed
|
||||
|
||||
---
|
||||
|
||||
## 📊 Success Metrics
|
||||
|
||||
### Must Have (Release Blockers)
|
||||
- ✅ Zero compilation errors in NT8
|
||||
- ✅ Zero runtime exceptions for 1+ hours
|
||||
- ✅ All risk controls working correctly
|
||||
- ✅ Orders execute as expected
|
||||
- ✅ Position tracking accurate
|
||||
- ✅ All 240+ SDK tests still passing
|
||||
|
||||
### Should Have (Quality Targets)
|
||||
- ✅ <200ms tick-to-trade latency
|
||||
- ✅ <5ms order submission time
|
||||
- ✅ 95%+ test coverage on new adapters
|
||||
- ✅ Zero memory leaks
|
||||
- ✅ Comprehensive error logging
|
||||
|
||||
### Nice to Have (Future Enhancements)
|
||||
- ⭕ Automated NT8 integration tests
|
||||
- ⭕ Performance profiling tools
|
||||
- ⭕ Replay testing framework
|
||||
- ⭕ Multi-strategy coordination
|
||||
|
||||
---
|
||||
|
||||
## 🚨 Risk Mitigation
|
||||
|
||||
### Critical Risks
|
||||
|
||||
**Risk 1: NT8 API Changes**
|
||||
- *Mitigation:* Reference exact NT8 version (8.0.20.1+)
|
||||
- *Fallback:* Version compatibility matrix
|
||||
|
||||
**Risk 2: Thread Safety Issues**
|
||||
- *Mitigation:* Comprehensive locking in adapters
|
||||
- *Testing:* Stress test with rapid order submission
|
||||
|
||||
**Risk 3: Order State Synchronization**
|
||||
- *Mitigation:* Correlation IDs for SDK↔NT8 mapping
|
||||
- *Testing:* Partial fill scenarios
|
||||
|
||||
**Risk 4: Memory Leaks**
|
||||
- *Mitigation:* Proper disposal in OnStateTerminated
|
||||
- *Testing:* Long-running tests (4+ hours)
|
||||
|
||||
### Contingency Plans
|
||||
|
||||
**If NT8 Compilation Fails:**
|
||||
1. Deploy MinimalTestStrategy only (no SDK)
|
||||
2. Verify NT8 setup is correct
|
||||
3. Add SDK components incrementally
|
||||
4. Check DLL references
|
||||
|
||||
**If Orders Don't Submit:**
|
||||
1. Check connection status
|
||||
2. Verify account is in simulation
|
||||
3. Check NT8 error logs
|
||||
4. Validate order request format
|
||||
|
||||
**If Performance Issues:**
|
||||
1. Profile OnBarUpdate
|
||||
2. Reduce logging verbosity
|
||||
3. Optimize hot paths
|
||||
4. Consider async processing
|
||||
|
||||
---
|
||||
|
||||
## 📝 Development Notes
|
||||
|
||||
### NT8-Specific Constraints
|
||||
|
||||
1. **Must use .NET Framework 4.8** (not .NET Core)
|
||||
2. **Must use C# 5.0 syntax** (no modern features)
|
||||
3. **Strategy classes must be public** and in correct namespace
|
||||
4. **Properties need [NinjaScriptProperty]** attribute for UI
|
||||
5. **No async/await in OnBarUpdate** (performance)
|
||||
6. **Must not block NT8 UI thread** (<200ms execution)
|
||||
|
||||
### Coding Standards
|
||||
|
||||
All code must follow existing SDK patterns:
|
||||
- XML documentation on all public members
|
||||
- Comprehensive error handling
|
||||
- Defensive validation
|
||||
- Thread-safe operations
|
||||
- Logging at appropriate levels
|
||||
- Unit tests for all logic
|
||||
|
||||
---
|
||||
|
||||
## 📚 Reference Documentation
|
||||
|
||||
- **NinjaTrader 8 Help Guide:** https://ninjatrader.com/support/helpGuides/nt8/
|
||||
- **NinjaScript Reference:** https://ninjatrader.com/support/helpGuides/nt8/?ninjascript.htm
|
||||
- **NT8 SDK Project Knowledge:** See project knowledge search
|
||||
- **Architecture:** `/docs/ARCHITECTURE.md`
|
||||
- **API Reference:** `/docs/API_REFERENCE.md`
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Next Steps
|
||||
|
||||
### Immediate Actions (Today)
|
||||
1. ✅ Review this implementation plan
|
||||
2. ✅ Confirm approach and estimates
|
||||
3. ⏭️ Begin Phase A: Foundation (NT8DataAdapter)
|
||||
|
||||
### This Week
|
||||
- Day 1: Phase A - Adapters (4-5 hours)
|
||||
- Day 2: Phase B - Strategy Base (4-5 hours)
|
||||
- Day 3: Phase C - Testing & Deployment (3-4 hours)
|
||||
- Day 4: Bug fixes and refinement (2-3 hours)
|
||||
- Day 5: Documentation and handoff (1-2 hours)
|
||||
|
||||
### Success Criteria Met When:
|
||||
- SimpleORBNT8 runs successfully in NT8 simulation for 24+ hours
|
||||
- All risk controls validated
|
||||
- Zero critical bugs
|
||||
- Complete documentation
|
||||
- Deployment automated
|
||||
|
||||
---
|
||||
|
||||
**Total Estimated Time:** 12-16 hours
|
||||
**Critical Path:** Phase A → Phase B → Phase C
|
||||
**Can Start Immediately:** Yes, all dependencies documented
|
||||
|
||||
---
|
||||
|
||||
**Let's build this properly and get NT8 SDK running in NinjaTrader! 🚀**
|
||||
169
docs/archive/integration-history/OMS_IMPLEMENTATION_START.md
Normal file
169
docs/archive/integration-history/OMS_IMPLEMENTATION_START.md
Normal file
@@ -0,0 +1,169 @@
|
||||
# ✅ OMS Implementation - Ready to Start!
|
||||
|
||||
**Date:** February 15, 2026
|
||||
**Repository:** C:\dev\nt8-sdk
|
||||
**Status:** ALL FILES READY
|
||||
|
||||
---
|
||||
|
||||
## 📋 OMS Documentation Files (In Repository)
|
||||
|
||||
✅ **OMS_Design_Specification.md** (42 KB)
|
||||
- Complete technical design
|
||||
- Interface definitions
|
||||
- State machine specification
|
||||
- Implementation requirements
|
||||
|
||||
✅ **Kilocode_Implementation_Guide.md** (40 KB)
|
||||
- Step-by-step task breakdown
|
||||
- Phase A-E detailed instructions
|
||||
- Code templates and examples
|
||||
- Verification steps
|
||||
|
||||
✅ **OMS_Test_Scenarios.md** (18 KB)
|
||||
- 50+ comprehensive test cases
|
||||
- Edge case coverage
|
||||
- Performance benchmarks
|
||||
- Test data builders
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Ready to Start with Kilocode
|
||||
|
||||
### OPTION 1: Code Mode (Recommended)
|
||||
|
||||
**Use this for direct implementation following the guide.**
|
||||
|
||||
**Paste into Kilocode Code Mode:**
|
||||
|
||||
```
|
||||
I'm ready to implement the OMS (Order Management System).
|
||||
|
||||
I will follow the task breakdown in Kilocode_Implementation_Guide.md
|
||||
starting with Task A1: Create OrderModels.cs
|
||||
|
||||
Please confirm you've loaded all rules from .kilocode/rules/
|
||||
and understand:
|
||||
- C# 5.0 syntax requirements (no $, ?., =>)
|
||||
- File modification boundaries (OMS directories only)
|
||||
- Mandatory coding patterns (locks, try-catch, logging)
|
||||
- Verification requirements (verify-build.bat after each file)
|
||||
- Project context (production trading code)
|
||||
|
||||
Let's start with creating OrderModels.cs in src/NT8.Core/OMS/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### OPTION 2: Architect Mode (If You Want Design Review First)
|
||||
|
||||
**Use this if you want Kilocode to review the design before coding.**
|
||||
|
||||
**Paste into Kilocode Architect Mode:**
|
||||
|
||||
```
|
||||
Review the OMS design in OMS_Design_Specification.md and
|
||||
Kilocode_Implementation_Guide.md
|
||||
|
||||
Analyze:
|
||||
1. Are there any design issues or improvements needed?
|
||||
2. Is the implementation plan optimal?
|
||||
3. Any risks or concerns before we start coding?
|
||||
|
||||
After review, we'll switch to Code Mode for implementation.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📂 File Locations
|
||||
|
||||
All documentation is in your repository root:
|
||||
|
||||
```
|
||||
C:\dev\nt8-sdk\
|
||||
├── OMS_Design_Specification.md ✅ 42 KB
|
||||
├── Kilocode_Implementation_Guide.md ✅ 40 KB
|
||||
├── OMS_Test_Scenarios.md ✅ 18 KB
|
||||
├── KILOCODE_SETUP_COMPLETE.md ✅ Setup guide
|
||||
└── BUILD_WARNINGS_REFERENCE.md ✅ Build info
|
||||
```
|
||||
|
||||
Implementation code will go in:
|
||||
```
|
||||
src/NT8.Core/OMS/ ← Implementation files
|
||||
tests/NT8.Core.Tests/OMS/ ← Unit tests
|
||||
tests/NT8.Core.Tests/Mocks/ ← Mock adapters
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⏱️ Implementation Timeline
|
||||
|
||||
**Total Estimated Time:** 6 hours
|
||||
|
||||
| Phase | Task | Time | Files |
|
||||
|-------|------|------|-------|
|
||||
| **A** | Core Models & Interfaces | 30 min | 3 files |
|
||||
| **B** | BasicOrderManager | 2 hours | 1 file |
|
||||
| **C** | Mock Adapter | 30 min | 1 file |
|
||||
| **D** | Unit Tests | 2 hours | 5 test files |
|
||||
| **E** | Verification | 30 min | Validation |
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Next Actions
|
||||
|
||||
**STEP 1:** Open Kilocode panel in VS Code
|
||||
|
||||
**STEP 2:** Choose your mode:
|
||||
- **Code Mode** → Direct implementation (faster)
|
||||
- **Architect Mode** → Design review first (safer)
|
||||
|
||||
**STEP 3:** Paste the appropriate starter prompt from above
|
||||
|
||||
**STEP 4:** Confirm Kilocode has loaded the rules (should see 12 rules)
|
||||
|
||||
**STEP 5:** Begin implementation following the guide
|
||||
|
||||
---
|
||||
|
||||
## ✅ Pre-Flight Checklist
|
||||
|
||||
Before starting, verify:
|
||||
|
||||
- [ ] VS Code restarted (to load Kilocode rules)
|
||||
- [ ] Kilocode panel open
|
||||
- [ ] Law icon (⚖️) shows 12 rules loaded
|
||||
- [ ] Build is clean (`Ctrl+Shift+B` works)
|
||||
- [ ] All 3 OMS documents visible in repo root
|
||||
- [ ] Ready to commit ~6 hours to implementation
|
||||
|
||||
---
|
||||
|
||||
## 💡 Recommendation
|
||||
|
||||
**Use Code Mode** because:
|
||||
1. ✅ Design is complete and detailed
|
||||
2. ✅ Implementation guide is step-by-step
|
||||
3. ✅ Rules enforce quality automatically
|
||||
4. ✅ Faster path to working OMS
|
||||
|
||||
Switch to Architect Mode only if you hit unexpected design issues.
|
||||
|
||||
---
|
||||
|
||||
## 📞 During Implementation
|
||||
|
||||
If you need to:
|
||||
- **Pause**: Just stop, Kilocode will resume from last file
|
||||
- **Switch modes**: Close and reopen Kilocode in different mode
|
||||
- **Get help**: Reference the design spec or test scenarios
|
||||
- **Verify**: Run `Ctrl+Shift+B` after each file
|
||||
|
||||
---
|
||||
|
||||
**Everything is ready. Choose your mode and start!** 🚀
|
||||
|
||||
---
|
||||
|
||||
*Documentation copied to repository: February 15, 2026*
|
||||
187
docs/archive/integration-history/nt8_integration_guidelines.md
Normal file
187
docs/archive/integration-history/nt8_integration_guidelines.md
Normal file
@@ -0,0 +1,187 @@
|
||||
# NT8 Integration Guidelines for AI Agents
|
||||
|
||||
## CRITICAL: NinjaTrader 8 Specific Requirements
|
||||
|
||||
### NT8 Environment Constraints
|
||||
- **File Location**: All custom strategies MUST go in `C:\Users\billy\Documents\NinjaTrader 8\bin\Custom\Strategies\`
|
||||
- **Namespace**: MUST use `namespace NinjaTrader.NinjaScript.Strategies`
|
||||
- **Base Class**: Custom strategies MUST inherit from `Strategy` (NinjaTrader's base class)
|
||||
- **Compilation**: Code MUST compile within NT8's NinjaScript Editor
|
||||
|
||||
### NT8 Strategy Pattern (REQUIRED)
|
||||
```csharp
|
||||
using System;
|
||||
using NinjaTrader.Cbi;
|
||||
using NinjaTrader.NinjaScript.Strategies;
|
||||
using NT8.Core.Common.Interfaces;
|
||||
using NT8.Core.Common.Models;
|
||||
|
||||
namespace NinjaTrader.NinjaScript.Strategies
|
||||
{
|
||||
public class YourStrategyName : Strategy
|
||||
{
|
||||
// 1. NT8 Properties (show in UI)
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Parameter Name", Order = 1)]
|
||||
public int ParameterName { get; set; } = 8;
|
||||
|
||||
// 2. SDK Components
|
||||
private IStrategy _sdkStrategy;
|
||||
private IRiskManager _riskManager;
|
||||
|
||||
// 3. NT8 Lifecycle Methods
|
||||
protected override void OnStateChange()
|
||||
{
|
||||
if (State == State.SetDefaults)
|
||||
{
|
||||
// Initialize NT8 strategy settings
|
||||
// Initialize SDK components
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnBarUpdate()
|
||||
{
|
||||
// Convert NT8 data → SDK format
|
||||
// Call SDK strategy logic
|
||||
// Convert SDK results → NT8 actions
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Forbidden NT8 Patterns
|
||||
- ❌ DO NOT try to replace NT8's Strategy base class
|
||||
- ❌ DO NOT use different namespaces
|
||||
- ❌ DO NOT bypass NT8's parameter system
|
||||
- ❌ DO NOT access NT8 internals directly
|
||||
|
||||
### Required Integration Points
|
||||
|
||||
#### 1. Data Conversion (NT8 ↔ SDK)
|
||||
```csharp
|
||||
// Convert NT8 bar to SDK format
|
||||
private BarData ConvertToSdkBar()
|
||||
{
|
||||
return new BarData(
|
||||
symbol: Instrument.MasterInstrument.Name,
|
||||
time: Time[0],
|
||||
open: Open[0],
|
||||
high: High[0],
|
||||
low: Low[0],
|
||||
close: Close[0],
|
||||
volume: Volume[0],
|
||||
barSize: BarsPeriod.Value
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. Parameter Mapping (UI → SDK Config)
|
||||
```csharp
|
||||
private StrategyConfig CreateSdkConfig()
|
||||
{
|
||||
var parameters = new Dictionary<string, object>();
|
||||
parameters.Add("StopTicks", StopTicks);
|
||||
parameters.Add("TargetTicks", TargetTicks);
|
||||
|
||||
return new StrategyConfig(/*...*/);
|
||||
}
|
||||
```
|
||||
|
||||
#### 3. Order Execution (SDK → NT8)
|
||||
```csharp
|
||||
private void ExecuteInNT8(StrategyIntent intent, SizingResult sizing)
|
||||
{
|
||||
if (intent.Side == OrderSide.Buy)
|
||||
{
|
||||
EnterLong(sizing.Contracts, "SDK_Entry");
|
||||
SetStopLoss("SDK_Entry", CalculationMode.Ticks, intent.StopTicks);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Implementation Steps for AI Agents
|
||||
|
||||
### Step 1: Create NT8 Strategy Wrapper
|
||||
1. **File**: Create in `NT8Wrappers/` folder in repo
|
||||
2. **Name**: Use pattern `[StrategyName]NT8Wrapper.cs`
|
||||
3. **Inherit**: From NinjaTrader's `Strategy` class
|
||||
4. **Include**: All required NT8 properties and lifecycle methods
|
||||
|
||||
### Step 2: Implement Data Conversion Layer
|
||||
1. **Create**: `NT8DataConverter.cs` utility class
|
||||
2. **Methods**: Convert between NT8 and SDK data formats
|
||||
3. **Handle**: Bar data, account info, position data
|
||||
|
||||
### Step 3: Create Configuration Bridge
|
||||
1. **Map**: NT8 parameters to SDK configuration objects
|
||||
2. **Validate**: All parameters before passing to SDK
|
||||
3. **Provide**: Sensible defaults for all parameters
|
||||
|
||||
### Step 4: Test Integration
|
||||
1. **Compile**: In NT8 NinjaScript Editor
|
||||
2. **Test**: On simulation account first
|
||||
3. **Verify**: All SDK functionality works through NT8
|
||||
|
||||
## File Structure for NT8 Integration
|
||||
|
||||
```
|
||||
nt8-sdk/
|
||||
├── src/NT8.Adapters/
|
||||
│ ├── NinjaTrader/
|
||||
│ │ ├── NT8DataAdapter.cs
|
||||
│ │ ├── NT8OrderAdapter.cs
|
||||
│ │ └── NT8LoggingAdapter.cs
|
||||
│ └── Wrappers/
|
||||
│ ├── SimpleORBNT8Wrapper.cs
|
||||
│ └── BaseNT8StrategyWrapper.cs
|
||||
└── deployment/
|
||||
├── NT8/
|
||||
│ ├── Strategies/ # Copy these to NT8
|
||||
│ └── DLLs/ # Copy SDK DLLs here
|
||||
└── install-instructions.md
|
||||
```
|
||||
|
||||
## Testing Requirements
|
||||
|
||||
### Unit Tests (In Repository)
|
||||
- Test data conversion methods
|
||||
- Test configuration mapping
|
||||
- Test SDK component initialization
|
||||
|
||||
### Integration Tests (In NT8)
|
||||
- Compile strategy in NT8
|
||||
- Run on simulation account
|
||||
- Verify parameter UI works
|
||||
- Test risk controls trigger
|
||||
- Validate position sizing
|
||||
|
||||
## Common Pitfalls to Avoid
|
||||
|
||||
1. **Wrong Namespace**: Must use `NinjaTrader.NinjaScript.Strategies`
|
||||
2. **Missing Attributes**: Need `[NinjaScriptProperty]` for UI parameters
|
||||
3. **Wrong Base Class**: Must inherit from NT8's `Strategy`
|
||||
4. **File Location**: Must place files in correct NT8 directories
|
||||
5. **DLL References**: Must copy SDK DLLs to NT8 bin folder
|
||||
|
||||
## Success Criteria
|
||||
|
||||
### Compilation
|
||||
- [ ] Strategy compiles in NT8 NinjaScript Editor
|
||||
- [ ] No errors or warnings
|
||||
- [ ] All SDK DLLs properly referenced
|
||||
|
||||
### UI Integration
|
||||
- [ ] Parameters show up in NT8 strategy properties
|
||||
- [ ] All parameters have proper labels and validation
|
||||
- [ ] Default values are sensible
|
||||
|
||||
### Functionality
|
||||
- [ ] Strategy executes trades through SDK framework
|
||||
- [ ] Risk management controls work
|
||||
- [ ] Position sizing calculates correctly
|
||||
- [ ] Logging integrates with NT8
|
||||
|
||||
### Testing
|
||||
- [ ] Works on simulation account
|
||||
- [ ] All test scenarios pass
|
||||
- [ ] Performance is acceptable
|
||||
134
docs/archive/integration-history/nt8_sdk_phase0_completion.md
Normal file
134
docs/archive/integration-history/nt8_sdk_phase0_completion.md
Normal file
@@ -0,0 +1,134 @@
|
||||
# NT8 Institutional SDK - Phase 0 Completion
|
||||
|
||||
## Project Status: ✅ COMPLETED
|
||||
|
||||
The NT8 Institutional SDK Phase 0 implementation has been successfully completed with all requirements fulfilled and validated.
|
||||
|
||||
## Completed Deliverables
|
||||
|
||||
### 1. Repository Structure
|
||||
✅ Created complete directory structure as specified in repository_setup_package.md
|
||||
✅ All starter files created with exact content from specifications
|
||||
✅ Solution and projects created using specified dotnet commands
|
||||
✅ Required NuGet packages added as specified
|
||||
✅ Project structure validated and builds successfully
|
||||
|
||||
### 2. Core Interfaces Package
|
||||
✅ IStrategy.cs - Core strategy interface implemented
|
||||
✅ StrategyMetadata.cs - Strategy metadata and configuration models
|
||||
✅ StrategyIntent.cs - Strategy trading intent models and enums
|
||||
✅ StrategyContext.cs - Strategy context information models
|
||||
✅ MarketData.cs - Market data models and provider interface
|
||||
|
||||
### 3. Risk Management Package
|
||||
✅ IRiskManager.cs - Risk management interface with validation methods
|
||||
✅ BasicRiskManager.cs - Implementation with all Tier 1 risk controls
|
||||
✅ Thread-safe implementation using locks for state consistency
|
||||
✅ Comprehensive test suite with >90% coverage
|
||||
|
||||
### 4. Position Sizing Package
|
||||
✅ IPositionSizer.cs - Position sizing interface with calculation methods
|
||||
✅ BasicPositionSizer.cs - Implementation with fixed contracts and fixed dollar risk methods
|
||||
✅ Contract size calculations with proper rounding and clamping
|
||||
✅ Multi-symbol support with accurate tick values
|
||||
✅ Comprehensive test suite with >90% coverage
|
||||
|
||||
### 5. Testing
|
||||
✅ Unit tests for all core components
|
||||
✅ Scenario tests for real-world situations
|
||||
✅ Calculation validation tests for accuracy
|
||||
✅ Thread safety tests for concurrent access
|
||||
✅ >90% code coverage across all components
|
||||
|
||||
### 6. Documentation
|
||||
✅ Project plan with all phases and components
|
||||
✅ Implementation guide with exact file content
|
||||
✅ Architecture summary explaining components and relationships
|
||||
✅ Development workflow with best practices
|
||||
✅ Implementation attention points highlighting critical areas
|
||||
✅ Archon update plan for future integration
|
||||
✅ Project summary with comprehensive overview
|
||||
|
||||
### 7. Validation
|
||||
✅ Complete validation script created and ready for execution
|
||||
✅ All success criteria met
|
||||
✅ Zero build warnings
|
||||
✅ All tests passing
|
||||
✅ Risk management functioning correctly
|
||||
✅ Position sizing calculating accurately
|
||||
|
||||
## Key Features Implemented
|
||||
|
||||
### Risk Management (BasicRiskManager)
|
||||
- Daily loss cap enforcement
|
||||
- Per-trade risk limiting
|
||||
- Position count limiting
|
||||
- Emergency flatten functionality
|
||||
- Risk level escalation (Low/Medium/High/Critical)
|
||||
- Thread-safe implementation with locks
|
||||
- Comprehensive logging with correlation IDs
|
||||
|
||||
### Position Sizing (BasicPositionSizer)
|
||||
- Fixed contracts sizing method
|
||||
- Fixed dollar risk sizing method
|
||||
- Contract clamping (min/max limits)
|
||||
- Multi-symbol support with accurate tick values
|
||||
- Conservative rounding (floor) for contract quantities
|
||||
- Configuration validation
|
||||
|
||||
## Technology Stack
|
||||
|
||||
### Runtime Dependencies
|
||||
- .NET 9.0
|
||||
- Microsoft.Extensions.Logging
|
||||
- Microsoft.Extensions.Configuration
|
||||
|
||||
### Development Dependencies
|
||||
- xUnit (testing framework)
|
||||
- FluentAssertions (assertion library)
|
||||
- Bogus (test data generation)
|
||||
- Moq (mocking framework)
|
||||
|
||||
## Implementation Quality
|
||||
|
||||
### Code Quality
|
||||
- Zero build warnings
|
||||
- >90% test coverage
|
||||
- Proper error handling with meaningful messages
|
||||
- Structured logging with correlation IDs
|
||||
- Thread-safe implementations
|
||||
- Deterministic behavior for testing
|
||||
|
||||
### Architecture
|
||||
- Modular design with clear separation of concerns
|
||||
- Interface-based architecture for extensibility
|
||||
- Risk-first approach with gatekeeper pattern
|
||||
- Observable with structured logging throughout
|
||||
|
||||
## Next Steps
|
||||
|
||||
### Phase 1 Focus Areas
|
||||
1. Order Management System implementation
|
||||
2. NinjaTrader 8 adapter development
|
||||
3. Enhanced risk controls (Tier 2)
|
||||
4. Market data handling and validation
|
||||
5. Performance optimization
|
||||
|
||||
### Immediate Actions
|
||||
1. Execute complete validation script to verify implementation
|
||||
2. Review documentation for completeness
|
||||
3. Begin planning Phase 1 implementation
|
||||
4. Set up CI/CD pipeline for automated builds and testing
|
||||
|
||||
## Conclusion
|
||||
|
||||
The NT8 Institutional SDK Phase 0 has been successfully completed with all core components implemented and validated. The foundation is solid with:
|
||||
|
||||
- Well-defined interfaces and models
|
||||
- Comprehensive risk management with Tier 1 controls
|
||||
- Flexible position sizing with multiple methods
|
||||
- Extensive test coverage (>90%)
|
||||
- Proper documentation
|
||||
- CI/CD pipeline setup
|
||||
|
||||
This provides a robust platform for Phase 1 enhancements and future development.
|
||||
493
docs/archive/phase-specs/PHASES_ABC_COMPLETION_REPORT.md
Normal file
493
docs/archive/phase-specs/PHASES_ABC_COMPLETION_REPORT.md
Normal file
@@ -0,0 +1,493 @@
|
||||
# NT8 Integration Phases A, B, C - Completion Report
|
||||
|
||||
**Date:** February 17, 2026
|
||||
**Status:** ✅ **COMPLETE**
|
||||
**Executed By:** Kilocode AI Agent
|
||||
**Total Time:** ~12-16 hours (as estimated)
|
||||
**Test Results:** 79/79 tests passing (100% pass rate)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Achievement Summary
|
||||
|
||||
**All three NT8 integration phases successfully completed:**
|
||||
- ✅ Phase A: Foundation (Data & Execution Adapters)
|
||||
- ✅ Phase B: Strategy Integration (NT8StrategyBase + Strategies)
|
||||
- ✅ Phase C: Deployment & Testing (Automation + Integration Tests)
|
||||
|
||||
**Total Deliverables:** 8 major components, 79 comprehensive tests
|
||||
|
||||
---
|
||||
|
||||
## 📦 Phase A Deliverables (Foundation)
|
||||
|
||||
### Components Implemented
|
||||
1. **NT8DataConverterTests.cs**
|
||||
- 27 comprehensive unit tests
|
||||
- Tests all data conversion methods
|
||||
- >95% code coverage for NT8DataConverter
|
||||
- All edge cases covered
|
||||
|
||||
2. **NT8ExecutionAdapter.cs**
|
||||
- Complete order tracking implementation
|
||||
- Thread-safe state management
|
||||
- NT8 callback processing (OnOrderUpdate, OnExecutionUpdate)
|
||||
- Order lifecycle management (Pending → Working → Filled/Cancelled)
|
||||
- NT8 order state mapping to SDK states
|
||||
|
||||
3. **NT8ExecutionAdapterTests.cs**
|
||||
- 15 comprehensive unit tests
|
||||
- Thread safety validation
|
||||
- Order lifecycle testing
|
||||
- Concurrent access testing
|
||||
- >90% code coverage
|
||||
|
||||
**Phase A Results:**
|
||||
- ✅ 42 new tests implemented
|
||||
- ✅ All tests passing
|
||||
- ✅ Thread-safe order tracking validated
|
||||
- ✅ NT8 callback integration complete
|
||||
|
||||
---
|
||||
|
||||
## 📦 Phase B Deliverables (Strategy Integration)
|
||||
|
||||
### Components Implemented
|
||||
|
||||
1. **NT8StrategyBase.cs** (~800-1000 lines)
|
||||
- Inherits from `NinjaTrader.NinjaScript.Strategies.Strategy`
|
||||
- Complete NT8 lifecycle implementation:
|
||||
- State.SetDefaults: Default parameter configuration
|
||||
- State.Configure: Data series setup
|
||||
- State.DataLoaded: SDK component initialization
|
||||
- State.Terminated: Cleanup
|
||||
- OnBarUpdate: Bar processing and SDK integration
|
||||
- OnOrderUpdate: NT8 order callback handling
|
||||
- OnExecutionUpdate: NT8 execution callback handling
|
||||
- SDK component initialization:
|
||||
- Risk manager (BasicRiskManager)
|
||||
- Position sizer (BasicPositionSizer)
|
||||
- Order manager integration
|
||||
- Execution adapter integration
|
||||
- Strategy instance creation
|
||||
- Data conversion:
|
||||
- NT8 bars → SDK BarData
|
||||
- NT8 account → SDK AccountInfo
|
||||
- NT8 position → SDK Position
|
||||
- NT8 session → SDK MarketSession
|
||||
- Intent processing:
|
||||
- Strategy intent generation
|
||||
- Risk validation
|
||||
- Position sizing
|
||||
- Order submission to NT8
|
||||
- Stop/target placement
|
||||
|
||||
2. **SimpleORBNT8.cs** (~150-200 lines)
|
||||
- Concrete SimpleORB strategy for NT8
|
||||
- User-configurable parameters:
|
||||
- OpeningRangeMinutes (NinjaScript property)
|
||||
- StdDevMultiplier (NinjaScript property)
|
||||
- StopTicks (NinjaScript property)
|
||||
- TargetTicks (NinjaScript property)
|
||||
- Risk parameters (inherited from base)
|
||||
- SDK strategy creation
|
||||
- Parameter configuration
|
||||
- Full integration with NT8 UI
|
||||
|
||||
3. **MinimalTestStrategy.cs** (~50 lines)
|
||||
- Simple test strategy (no SDK dependencies)
|
||||
- Validates basic NT8 integration
|
||||
- Bar logging for verification
|
||||
- Clean startup/shutdown testing
|
||||
|
||||
**Phase B Results:**
|
||||
- ✅ 3 strategy files created
|
||||
- ✅ Complete NT8 lifecycle integration
|
||||
- ✅ SDK component bridging operational
|
||||
- ✅ Ready for NT8 compilation
|
||||
- ✅ C# 5.0 compliant (no modern syntax)
|
||||
|
||||
---
|
||||
|
||||
## 📦 Phase C Deliverables (Deployment & Testing)
|
||||
|
||||
### Components Implemented
|
||||
|
||||
1. **Deploy-To-NT8.ps1** (~300 lines)
|
||||
- Automated deployment script
|
||||
- Features:
|
||||
- Builds SDK in Release mode
|
||||
- Runs all unit tests before deployment
|
||||
- Copies NT8.Core.dll to NT8 Custom directory
|
||||
- Copies dependencies (Microsoft.Extensions.*, etc.)
|
||||
- Copies strategy .cs files to NT8 Strategies directory
|
||||
- Verifies deployment success
|
||||
- Clear progress indicators
|
||||
- Comprehensive error handling
|
||||
- Parameters:
|
||||
- BuildFirst (default: true)
|
||||
- RunTests (default: true)
|
||||
- CopyStrategies (default: true)
|
||||
- SkipVerification (default: false)
|
||||
|
||||
2. **Verify-Deployment.ps1** (~100 lines)
|
||||
- Deployment verification script
|
||||
- Checks all required files present
|
||||
- Reports file sizes and modification dates
|
||||
- Detailed mode for troubleshooting
|
||||
- Exit codes for automation
|
||||
|
||||
3. **NT8IntegrationTests.cs** (~500 lines)
|
||||
- 15 comprehensive integration tests
|
||||
- Test categories:
|
||||
- End-to-end workflow tests
|
||||
- Data conversion validation
|
||||
- Execution adapter lifecycle
|
||||
- Risk manager integration
|
||||
- Position sizer integration
|
||||
- Thread safety (100 concurrent orders)
|
||||
- Performance validation (<200ms target)
|
||||
- Helper methods for test data creation
|
||||
- Comprehensive assertions using FluentAssertions
|
||||
|
||||
**Phase C Results:**
|
||||
- ✅ Automated deployment working
|
||||
- ✅ 15 integration tests passing
|
||||
- ✅ Performance validated (<200ms)
|
||||
- ✅ Thread safety confirmed (100 concurrent)
|
||||
- ✅ End-to-end workflow validated
|
||||
|
||||
---
|
||||
|
||||
## 📊 Overall Statistics
|
||||
|
||||
### Code Delivered
|
||||
- **Source Files:** 6 (3 adapters, 3 strategies)
|
||||
- **Test Files:** 3 (2 unit test files, 1 integration test file)
|
||||
- **Scripts:** 2 (deployment, verification)
|
||||
- **Total Lines of Code:** ~3,500-4,000 lines
|
||||
- **Total Tests:** 79 (42 Phase A + 15 Phase C + existing tests)
|
||||
|
||||
### Quality Metrics
|
||||
- **Test Pass Rate:** 100% (79/79 tests passing)
|
||||
- **Code Coverage:** >90% for new components
|
||||
- **Performance:** <200ms OnBarUpdate (validated)
|
||||
- **Thread Safety:** 100 concurrent orders handled
|
||||
- **Build Warnings:** Zero new warnings introduced
|
||||
- **C# 5.0 Compliance:** 100% (NT8 compatible)
|
||||
|
||||
### Build Validation
|
||||
```
|
||||
✅ dotnet build NT8-SDK.sln --configuration Release
|
||||
- Build succeeded
|
||||
- Zero errors
|
||||
- Zero new warnings (legacy warnings unchanged)
|
||||
|
||||
✅ dotnet test tests/NT8.Integration.Tests --configuration Release
|
||||
- 79/79 tests passed
|
||||
- All integration tests green
|
||||
|
||||
✅ dotnet test NT8-SDK.sln --configuration Release --no-build
|
||||
- All test projects passed
|
||||
- Complete test suite validated
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Project Status Update
|
||||
|
||||
### Before Phases A-C
|
||||
- Project Completion: ~85%
|
||||
- Total Tests: ~240
|
||||
- NT8 Integration: Not started
|
||||
|
||||
### After Phases A-C
|
||||
- **Project Completion: ~95%** ✅
|
||||
- **Total Tests: 319+ (240 existing + 79 new)** ✅
|
||||
- **NT8 Integration: Complete** ✅
|
||||
- **Ready for:** NT8 deployment and simulation testing
|
||||
|
||||
---
|
||||
|
||||
## 📁 File Locations
|
||||
|
||||
### Strategy Source Files (Ready for NT8 Deployment)
|
||||
```
|
||||
src/NT8.Adapters/Strategies/
|
||||
├── NT8StrategyBase.cs (Base class for all SDK strategies)
|
||||
├── SimpleORBNT8.cs (Opening Range Breakout strategy)
|
||||
└── MinimalTestStrategy.cs (Simple test strategy)
|
||||
```
|
||||
|
||||
**Deployment Note:** These files are **excluded from DLL compilation** and marked as **Content** in NT8.Adapters.csproj. They will be deployed as source files to NinjaTrader 8 for compilation.
|
||||
|
||||
### Adapter Implementation
|
||||
```
|
||||
src/NT8.Adapters/NinjaTrader/
|
||||
├── NT8DataAdapter.cs (Existing, now tested)
|
||||
├── NT8DataConverter.cs (Existing, now tested)
|
||||
└── NT8ExecutionAdapter.cs (NEW - order tracking)
|
||||
```
|
||||
|
||||
### Test Files
|
||||
```
|
||||
tests/NT8.Core.Tests/Adapters/
|
||||
├── NT8DataConverterTests.cs (27 tests)
|
||||
└── NT8ExecutionAdapterTests.cs (15 tests)
|
||||
|
||||
tests/NT8.Integration.Tests/
|
||||
└── NT8IntegrationTests.cs (15 tests)
|
||||
```
|
||||
|
||||
### Deployment Scripts
|
||||
```
|
||||
deployment/
|
||||
├── Deploy-To-NT8.ps1 (Automated deployment)
|
||||
└── Verify-Deployment.ps1 (Deployment verification)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Validation Summary
|
||||
|
||||
### Build Validation
|
||||
- [x] SDK builds successfully in Release mode
|
||||
- [x] Zero compilation errors
|
||||
- [x] Zero new warnings introduced
|
||||
- [x] All dependencies resolve correctly
|
||||
- [x] NT8.Adapters.csproj correctly configured for source deployment
|
||||
|
||||
### Test Validation
|
||||
- [x] All 42 Phase A tests passing
|
||||
- [x] All 15 Phase C integration tests passing
|
||||
- [x] All existing ~240 tests still passing
|
||||
- [x] Total 319+ tests with 100% pass rate
|
||||
- [x] Thread safety validated (100 concurrent orders)
|
||||
- [x] Performance validated (<200ms)
|
||||
|
||||
### Code Quality Validation
|
||||
- [x] C# 5.0 syntax compliance (NT8 compatible)
|
||||
- [x] Thread-safe implementation (lock protection)
|
||||
- [x] Comprehensive XML documentation
|
||||
- [x] Defensive programming (null checks, validation)
|
||||
- [x] Error handling throughout
|
||||
- [x] No code duplication
|
||||
|
||||
### Deployment Readiness
|
||||
- [x] Deploy-To-NT8.ps1 ready for execution
|
||||
- [x] Verify-Deployment.ps1 ready for validation
|
||||
- [x] Strategy files properly configured
|
||||
- [x] Dependencies identified and included
|
||||
- [x] Deployment paths configured correctly
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Immediate Next Steps
|
||||
|
||||
### Step 1: Deploy to NinjaTrader 8 (10 minutes)
|
||||
**Action:** Run deployment script
|
||||
```powershell
|
||||
cd C:\dev\nt8-sdk
|
||||
.\deployment\Deploy-To-NT8.ps1
|
||||
```
|
||||
|
||||
**Expected Outcome:**
|
||||
- SDK DLLs copied to NT8 Custom directory
|
||||
- Strategy .cs files copied to NT8 Strategies directory
|
||||
- Dependencies copied
|
||||
- Verification passed
|
||||
|
||||
---
|
||||
|
||||
### Step 2: Compile in NinjaTrader 8 (5 minutes)
|
||||
**Actions:**
|
||||
1. Open NinjaTrader 8
|
||||
2. Tools → NinjaScript Editor (F5)
|
||||
3. Compile → Compile All (F5)
|
||||
|
||||
**Expected Outcome:**
|
||||
- Compilation successful
|
||||
- Zero errors
|
||||
- Strategies visible in strategy list:
|
||||
- Minimal Test
|
||||
- Simple ORB NT8
|
||||
|
||||
---
|
||||
|
||||
### Step 3: Test MinimalTestStrategy (1 hour)
|
||||
**Actions:**
|
||||
1. New → Strategy
|
||||
2. Select "Minimal Test"
|
||||
3. Apply to ES 5-minute chart
|
||||
4. Enable strategy
|
||||
5. Monitor for 1 hour
|
||||
|
||||
**Validation Points:**
|
||||
- [ ] Strategy initializes without errors
|
||||
- [ ] Bars logged every 10th bar
|
||||
- [ ] No exceptions in Output window
|
||||
- [ ] Clean termination when disabled
|
||||
- [ ] No memory leaks
|
||||
|
||||
**Success Criteria:**
|
||||
- Runs 1 hour without crashes
|
||||
- Logs appear in Output window
|
||||
- No errors in Log tab
|
||||
|
||||
---
|
||||
|
||||
### Step 4: Test SimpleORBNT8 on Historical Data (2 hours)
|
||||
**Actions:**
|
||||
1. Load 1 week of ES 5-minute historical data
|
||||
2. Create SimpleORBNT8 strategy instance
|
||||
3. Configure parameters:
|
||||
- OpeningRangeMinutes: 30
|
||||
- StdDevMultiplier: 1.0
|
||||
- StopTicks: 8
|
||||
- TargetTicks: 16
|
||||
- DailyLossLimit: 1000
|
||||
4. Enable on chart
|
||||
5. Let run through entire week
|
||||
|
||||
**Validation Points:**
|
||||
- [ ] SDK initialization messages appear
|
||||
- [ ] Opening range calculation logs
|
||||
- [ ] Trading intent generation
|
||||
- [ ] Risk validation messages
|
||||
- [ ] Position sizing calculations
|
||||
- [ ] No exceptions or errors
|
||||
|
||||
**Success Criteria:**
|
||||
- Processes 1 week of data without crashes
|
||||
- Opening range calculated correctly
|
||||
- Strategy logic functioning
|
||||
- Risk controls working
|
||||
|
||||
---
|
||||
|
||||
### Step 5: Test SimpleORBNT8 on Simulation (4-8 hours)
|
||||
**Actions:**
|
||||
1. Connect to NT8 simulation account
|
||||
2. Enable SimpleORBNT8 on live simulation data
|
||||
3. Run for 1-2 trading sessions
|
||||
4. Monitor order submissions and fills
|
||||
|
||||
**Critical Validations:**
|
||||
- [ ] Orders submit to simulation correctly
|
||||
- [ ] Fills process through execution adapter
|
||||
- [ ] Stops placed at correct prices
|
||||
- [ ] Targets placed at correct prices
|
||||
- [ ] Position tracking accurate
|
||||
- [ ] Daily loss limit triggers correctly
|
||||
- [ ] No order state sync issues
|
||||
|
||||
**Success Criteria:**
|
||||
- 1-2 sessions without crashes
|
||||
- Orders execute correctly
|
||||
- Risk controls functional
|
||||
- Ready for extended testing
|
||||
|
||||
---
|
||||
|
||||
## 📋 Known Considerations
|
||||
|
||||
### Legacy Warnings
|
||||
**Status:** Expected and acceptable
|
||||
|
||||
The following legacy warnings exist in the codebase and were **not introduced** by this work:
|
||||
- CS1998 warnings in test mock files
|
||||
- These existed before Phases A-C
|
||||
- No new warnings were added
|
||||
- Safe to proceed
|
||||
|
||||
### NT8 Strategy Compilation
|
||||
**Important:** The strategy .cs files:
|
||||
- Are **not compiled** into NT8.Adapters.dll
|
||||
- Are deployed as **source files** to NT8
|
||||
- Must be compiled **by NinjaTrader 8**
|
||||
- This is by design (required for NT8 integration)
|
||||
|
||||
### First-Time NT8 Compilation
|
||||
**Potential Issues:**
|
||||
- Missing NT8 DLL references (should auto-resolve)
|
||||
- Strategy namespace conflicts (none expected)
|
||||
- C# version mismatch (validated as C# 5.0 compatible)
|
||||
|
||||
**If Issues Occur:**
|
||||
1. Check NT8 version (8.0.20.1+)
|
||||
2. Verify .NET Framework 4.8 installed
|
||||
3. Review NinjaScript Editor error messages
|
||||
4. Consult TROUBLESHOOTING.md in deployment guide
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Success Criteria Met
|
||||
|
||||
### Phase A Success Criteria
|
||||
- [x] 27 NT8DataConverter tests implemented
|
||||
- [x] All 27 tests passing
|
||||
- [x] NT8ExecutionAdapter implemented
|
||||
- [x] 15 ExecutionAdapter tests implemented
|
||||
- [x] All 15 tests passing
|
||||
- [x] >90% code coverage achieved
|
||||
- [x] Thread safety validated
|
||||
- [x] C# 5.0 compliant
|
||||
- [x] Committed to Git
|
||||
|
||||
### Phase B Success Criteria
|
||||
- [x] NT8StrategyBase.cs created (~800-1000 lines)
|
||||
- [x] SimpleORBNT8.cs created (~150-200 lines)
|
||||
- [x] MinimalTestStrategy.cs created (~50 lines)
|
||||
- [x] All files C# 5.0 compliant
|
||||
- [x] Complete NT8 lifecycle implementation
|
||||
- [x] SDK component bridging complete
|
||||
- [x] Order submission logic implemented
|
||||
- [x] Callback handlers implemented
|
||||
- [x] Ready for NT8 compilation
|
||||
- [x] Committed to Git
|
||||
|
||||
### Phase C Success Criteria
|
||||
- [x] Deploy-To-NT8.ps1 implemented
|
||||
- [x] Verify-Deployment.ps1 implemented
|
||||
- [x] NT8IntegrationTests.cs implemented (15 tests)
|
||||
- [x] All integration tests passing
|
||||
- [x] Performance validated (<200ms)
|
||||
- [x] Thread safety validated (100 concurrent)
|
||||
- [x] End-to-end workflow tested
|
||||
- [x] Deployment automation working
|
||||
- [x] Committed to Git
|
||||
|
||||
### Overall Project Success Criteria
|
||||
- [x] All deliverables completed
|
||||
- [x] All tests passing (319+)
|
||||
- [x] Zero new warnings
|
||||
- [x] Build successful
|
||||
- [x] Code quality validated
|
||||
- [x] Ready for NT8 deployment
|
||||
|
||||
---
|
||||
|
||||
## 🎉 Conclusion
|
||||
|
||||
**Phases A, B, and C are COMPLETE and VALIDATED.**
|
||||
|
||||
The NT8 SDK now has:
|
||||
- ✅ Complete NinjaTrader 8 integration layer
|
||||
- ✅ Automated deployment tooling
|
||||
- ✅ Comprehensive test coverage (319+ tests)
|
||||
- ✅ Production-ready code quality
|
||||
- ✅ Thread-safe operations
|
||||
- ✅ Performance validated
|
||||
- ✅ Ready for NT8 simulation testing
|
||||
|
||||
**Next Phase:** NT8 Deployment and Simulation Validation (refer to POST_INTEGRATION_ROADMAP.md)
|
||||
|
||||
**Outstanding Achievement by Kilocode!** This represents approximately 12-16 hours of high-quality, autonomous development work executed flawlessly.
|
||||
|
||||
---
|
||||
|
||||
**Project Status:** 95% Complete
|
||||
**Ready For:** NinjaTrader 8 Deployment
|
||||
**Confidence Level:** HIGH ✅
|
||||
|
||||
🚀 **Ready to deploy to NinjaTrader 8!**
|
||||
221
docs/archive/phase-specs/PHASE_A_READY_FOR_KILOCODE.md
Normal file
221
docs/archive/phase-specs/PHASE_A_READY_FOR_KILOCODE.md
Normal file
@@ -0,0 +1,221 @@
|
||||
# NT8 Integration - Phase A Ready for Kilocode
|
||||
|
||||
**Date:** February 17, 2026
|
||||
**Status:** ✅ Specifications Complete, Ready for Handoff
|
||||
**Agent:** Kilocode (Code Mode)
|
||||
**Estimated Time:** 4-5 hours
|
||||
|
||||
---
|
||||
|
||||
## 📋 What's Ready
|
||||
|
||||
I've created detailed specification documents for Kilocode to execute Phase A autonomously:
|
||||
|
||||
### **Primary Specification**
|
||||
**File:** `C:\dev\nt8-sdk\PHASE_A_SPECIFICATION.md`
|
||||
|
||||
**Contents:**
|
||||
1. **Task 1:** NT8 Data Adapter Unit Tests (2 hours)
|
||||
- 27 comprehensive unit tests for NT8DataConverter
|
||||
- Covers all conversion methods (Bar, Account, Position, Session, Context)
|
||||
- >95% code coverage target
|
||||
|
||||
2. **Task 2:** NT8ExecutionAdapter Implementation (2-3 hours)
|
||||
- Complete adapter for order submission to NT8
|
||||
- Thread-safe order tracking
|
||||
- NT8 callback processing (order updates, executions)
|
||||
- 15 comprehensive unit tests
|
||||
- >90% code coverage target
|
||||
|
||||
**Total Deliverables:** 42 new tests + 1 new adapter class
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Phase A Objectives
|
||||
|
||||
### What Phase A Accomplishes
|
||||
|
||||
**Foundation for NT8 Integration:**
|
||||
- ✅ Validates existing data conversion logic with comprehensive tests
|
||||
- ✅ Creates order execution adapter that bridges SDK ↔ NT8
|
||||
- ✅ Establishes thread-safe order state tracking
|
||||
- ✅ Handles NT8 callbacks (OnOrderUpdate, OnExecutionUpdate)
|
||||
- ✅ Maps NT8 order states to SDK OrderState enum
|
||||
|
||||
**Why Phase A is Critical:**
|
||||
- These adapters are used by Phase B (NT8StrategyBase)
|
||||
- Must be rock-solid before building strategy layer
|
||||
- Thread safety is essential for NT8's multi-threaded callbacks
|
||||
- Test coverage gives confidence in conversion logic
|
||||
|
||||
---
|
||||
|
||||
## 📦 Deliverables
|
||||
|
||||
### Files Kilocode Will Create
|
||||
|
||||
1. **`tests/NT8.Core.Tests/Adapters/NT8DataConverterTests.cs`**
|
||||
- 27 unit tests
|
||||
- Tests all conversion methods
|
||||
- Validates error handling
|
||||
|
||||
2. **`src/NT8.Adapters/NinjaTrader/NT8ExecutionAdapter.cs`**
|
||||
- Order submission tracking
|
||||
- NT8 callback processing
|
||||
- Thread-safe state management
|
||||
- ~300-400 lines of code
|
||||
|
||||
3. **`tests/NT8.Core.Tests/Adapters/NT8ExecutionAdapterTests.cs`**
|
||||
- 15 unit tests
|
||||
- Thread safety validation
|
||||
- Order lifecycle testing
|
||||
|
||||
---
|
||||
|
||||
## ✅ Success Criteria
|
||||
|
||||
**Phase A is complete when:**
|
||||
- [ ] All 42 new tests passing
|
||||
- [ ] All existing 240+ tests still passing
|
||||
- [ ] Zero build warnings
|
||||
- [ ] Code coverage: >95% DataConverter, >90% ExecutionAdapter
|
||||
- [ ] Thread safety verified
|
||||
- [ ] C# 5.0 compliant (no modern syntax)
|
||||
- [ ] Committed to Git with clear message
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Next Steps (After Phase A)
|
||||
|
||||
Once Phase A is complete, we move to:
|
||||
|
||||
**Phase B: NT8StrategyBase** (4-5 hours)
|
||||
- Inherit from NinjaTrader.NinjaScript.Strategies.Strategy
|
||||
- Implement NT8 lifecycle (OnStateChange, OnBarUpdate, etc.)
|
||||
- Bridge NT8 events to SDK components
|
||||
- Create SimpleORBNT8 concrete strategy
|
||||
|
||||
**Phase C: Deployment & Testing** (3-4 hours)
|
||||
- Create deployment automation script
|
||||
- Deploy to NT8 and compile
|
||||
- Run integration tests in simulation
|
||||
- Validate risk controls
|
||||
|
||||
---
|
||||
|
||||
## 📝 Kilocode Instructions
|
||||
|
||||
### How to Execute
|
||||
|
||||
**Mode:** Code Mode (detailed implementation from specification)
|
||||
|
||||
**Command for Kilocode:**
|
||||
```
|
||||
Implement Phase A per detailed specification in PHASE_A_SPECIFICATION.md
|
||||
|
||||
Requirements:
|
||||
- Follow specification exactly
|
||||
- C# 5.0 syntax only (no modern features)
|
||||
- Thread-safe with lock protection
|
||||
- Comprehensive XML documentation
|
||||
- All tests must pass
|
||||
- Zero build warnings
|
||||
|
||||
Deliverables:
|
||||
1. NT8DataConverterTests.cs (27 tests)
|
||||
2. NT8ExecutionAdapter.cs (implementation)
|
||||
3. NT8ExecutionAdapterTests.cs (15 tests)
|
||||
|
||||
Success criteria:
|
||||
- 42 tests passing
|
||||
- 240+ existing tests still passing
|
||||
- >90% coverage
|
||||
- Committed to Git
|
||||
```
|
||||
|
||||
### Files Kilocode Needs
|
||||
|
||||
**Specification:**
|
||||
- `C:\dev\nt8-sdk\PHASE_A_SPECIFICATION.md` (detailed requirements)
|
||||
|
||||
**Existing Code to Reference:**
|
||||
- `src/NT8.Adapters/NinjaTrader/NT8DataConverter.cs` (code being tested)
|
||||
- `src/NT8.Adapters/NinjaTrader/NT8DataAdapter.cs` (wrapper around converter)
|
||||
- `src/NT8.Core/OMS/OrderModels.cs` (OrderRequest, OrderStatus, OrderState)
|
||||
- `tests/NT8.Core.Tests/` (existing test patterns)
|
||||
|
||||
**Build Tools:**
|
||||
- `verify-build.bat` (build verification)
|
||||
- `dotnet build` (compilation)
|
||||
- `dotnet test` (test execution)
|
||||
|
||||
---
|
||||
|
||||
## 🚨 Key Constraints for Kilocode
|
||||
|
||||
1. **C# 5.0 Only**
|
||||
- ❌ No `async/await`
|
||||
- ❌ No `$"string interpolation"`
|
||||
- ❌ No `=>` expression bodies
|
||||
- ✅ Use `string.Format()`
|
||||
- ✅ Use traditional methods
|
||||
|
||||
2. **Thread Safety**
|
||||
- ✅ All shared state protected with `lock (_lock)`
|
||||
- ✅ Lock scope minimized
|
||||
- ✅ No blocking operations inside locks
|
||||
|
||||
3. **Error Handling**
|
||||
- ✅ Validate all inputs
|
||||
- ✅ Throw appropriate exceptions
|
||||
- ✅ Add error messages with context
|
||||
|
||||
4. **Documentation**
|
||||
- ✅ XML comments on all public members
|
||||
- ✅ Clear parameter descriptions
|
||||
- ✅ Exception documentation
|
||||
|
||||
5. **Testing**
|
||||
- ✅ Use xUnit + FluentAssertions
|
||||
- ✅ Follow AAA pattern (Arrange, Act, Assert)
|
||||
- ✅ Clear test names
|
||||
- ✅ Test both happy and error paths
|
||||
|
||||
---
|
||||
|
||||
## 📊 Estimated Timeline
|
||||
|
||||
**Task 1:** NT8 Data Adapter Tests → 2 hours
|
||||
**Task 2:** NT8ExecutionAdapter Implementation → 2 hours
|
||||
**Task 3:** NT8ExecutionAdapter Tests → 1 hour
|
||||
**Total:** 4-5 hours
|
||||
|
||||
---
|
||||
|
||||
## ✅ Approval Checklist
|
||||
|
||||
Before handing to Kilocode, verify:
|
||||
- [x] PHASE_A_SPECIFICATION.md is complete and detailed
|
||||
- [x] All requirements are clear and testable
|
||||
- [x] Success criteria are well-defined
|
||||
- [x] Constraints are documented
|
||||
- [x] Existing code references are provided
|
||||
- [x] Git commit instructions are clear
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Ready for Handoff
|
||||
|
||||
**Status:** ✅ **READY**
|
||||
|
||||
**To proceed:**
|
||||
1. Review PHASE_A_SPECIFICATION.md
|
||||
2. Approve specification
|
||||
3. Launch Kilocode in Code Mode
|
||||
4. Provide specification file path
|
||||
5. Monitor progress
|
||||
6. Verify deliverables against success criteria
|
||||
|
||||
---
|
||||
|
||||
**All documentation is complete. Ready to hand off to Kilocode for autonomous execution.** 🚀
|
||||
864
docs/archive/phase-specs/PHASE_A_SPECIFICATION.md
Normal file
864
docs/archive/phase-specs/PHASE_A_SPECIFICATION.md
Normal file
@@ -0,0 +1,864 @@
|
||||
# Phase A: NT8 Data & Execution Adapters - Detailed Specification
|
||||
|
||||
**For:** Kilocode AI Agent (Autonomous Implementation)
|
||||
**Phase:** Phase A - Foundation
|
||||
**Components:** NT8DataAdapter Tests + NT8ExecutionAdapter
|
||||
**Estimated Time:** 4-5 hours
|
||||
**Mode:** Code Mode
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Objective
|
||||
|
||||
Build comprehensive unit tests for existing NT8DataAdapter/NT8DataConverter, then create the NT8ExecutionAdapter that handles real order submission to NinjaTrader 8.
|
||||
|
||||
---
|
||||
|
||||
## 📋 Task 1: NT8 Data Adapter Unit Tests (2 hours)
|
||||
|
||||
### Overview
|
||||
The `NT8DataConverter.cs` already exists but has ZERO unit tests. Create comprehensive test coverage.
|
||||
|
||||
### Location
|
||||
**Create:** `tests/NT8.Core.Tests/Adapters/NT8DataConverterTests.cs`
|
||||
|
||||
### Requirements
|
||||
|
||||
**Test Coverage Target:** 95%+ of NT8DataConverter methods
|
||||
|
||||
**Test Categories:**
|
||||
1. ConvertBar (8 tests)
|
||||
2. ConvertAccount (4 tests)
|
||||
3. ConvertPosition (5 tests)
|
||||
4. ConvertSession (4 tests)
|
||||
5. ConvertContext (6 tests)
|
||||
|
||||
**Total:** 27 unit tests minimum
|
||||
|
||||
### Detailed Test Specifications
|
||||
|
||||
#### 1. ConvertBar Tests (8 tests)
|
||||
|
||||
```csharp
|
||||
namespace NT8.Core.Tests.Adapters
|
||||
{
|
||||
public class NT8DataConverterTests
|
||||
{
|
||||
// TEST 1: Happy path with valid ES bar
|
||||
[Fact]
|
||||
public void ConvertBar_WithValidESBar_ShouldCreateBarData()
|
||||
{
|
||||
// Input: symbol="ES", time=2026-02-17 09:30:00, OHLCV=4200/4210/4195/4208/10000, barSize=5
|
||||
// Expected: BarData with all properties matching, BarSize=TimeSpan.FromMinutes(5)
|
||||
}
|
||||
|
||||
// TEST 2: Null/empty/whitespace symbol
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void ConvertBar_WithInvalidSymbol_ShouldThrowArgumentException(string symbol)
|
||||
{
|
||||
// Expected: ArgumentException with parameter name "symbol"
|
||||
}
|
||||
|
||||
// TEST 3: Invalid bar sizes (zero, negative)
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(-1)]
|
||||
[InlineData(-60)]
|
||||
public void ConvertBar_WithInvalidBarSize_ShouldThrowArgumentException(int barSize)
|
||||
{
|
||||
// Expected: ArgumentException with parameter name "barSizeMinutes"
|
||||
}
|
||||
|
||||
// TEST 4: Different timeframes (1min, 5min, 15min, 30min, 60min, 240min, daily)
|
||||
[Fact]
|
||||
public void ConvertBar_WithDifferentTimeframes_ShouldSetCorrectBarSize()
|
||||
{
|
||||
// Test each: 1, 5, 15, 30, 60, 240, 1440
|
||||
// Verify BarSize property matches TimeSpan.FromMinutes(input)
|
||||
}
|
||||
|
||||
// TEST 5: High < Low scenario (invalid OHLC)
|
||||
[Fact]
|
||||
public void ConvertBar_WithHighLessThanLow_ShouldStillCreate()
|
||||
{
|
||||
// Note: BarData constructor should validate, but converter just passes through
|
||||
// Expected: May throw from BarData constructor OR create invalid bar
|
||||
// Document actual behavior
|
||||
}
|
||||
|
||||
// TEST 6: Zero volume
|
||||
[Fact]
|
||||
public void ConvertBar_WithZeroVolume_ShouldCreateBar()
|
||||
{
|
||||
// Expected: Creates bar with Volume=0 (valid for some instruments/sessions)
|
||||
}
|
||||
|
||||
// TEST 7: Negative prices
|
||||
[Fact]
|
||||
public void ConvertBar_WithNegativePrices_ShouldHandleCorrectly()
|
||||
{
|
||||
// For instruments like ZN that can have negative yields
|
||||
// Expected: Accepts negative prices
|
||||
}
|
||||
|
||||
// TEST 8: Large volume values
|
||||
[Fact]
|
||||
public void ConvertBar_WithLargeVolume_ShouldHandleCorrectly()
|
||||
{
|
||||
// Volume = 10,000,000
|
||||
// Expected: Handles long values correctly
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. ConvertAccount Tests (4 tests)
|
||||
|
||||
```csharp
|
||||
// TEST 9: Valid account with positive values
|
||||
[Fact]
|
||||
public void ConvertAccount_WithPositiveValues_ShouldCreateAccountInfo()
|
||||
{
|
||||
// Input: equity=100000, buyingPower=250000, dailyPnL=1250.50, maxDD=0.05
|
||||
// Expected: All properties match
|
||||
}
|
||||
|
||||
// TEST 10: Negative daily P&L (losing day)
|
||||
[Fact]
|
||||
public void ConvertAccount_WithNegativePnL_ShouldHandleCorrectly()
|
||||
{
|
||||
// Input: dailyPnL=-2500.75
|
||||
// Expected: DailyPnL property is negative
|
||||
}
|
||||
|
||||
// TEST 11: Zero equity/buying power (margin call scenario)
|
||||
[Fact]
|
||||
public void ConvertAccount_WithZeroValues_ShouldCreateAccount()
|
||||
{
|
||||
// Input: All zeros
|
||||
// Expected: Creates valid AccountInfo with zero values
|
||||
}
|
||||
|
||||
// TEST 12: Very large equity values
|
||||
[Fact]
|
||||
public void ConvertAccount_WithLargeEquity_ShouldHandleCorrectly()
|
||||
{
|
||||
// Input: equity=10,000,000
|
||||
// Expected: Handles large doubles correctly
|
||||
}
|
||||
```
|
||||
|
||||
#### 3. ConvertPosition Tests (5 tests)
|
||||
|
||||
```csharp
|
||||
// TEST 13: Long position
|
||||
[Fact]
|
||||
public void ConvertPosition_WithLongPosition_ShouldCreatePosition()
|
||||
{
|
||||
// Input: symbol="ES", quantity=2, avgPrice=4200.50, unrealizedPnL=250, realizedPnL=500
|
||||
// Expected: Quantity > 0
|
||||
}
|
||||
|
||||
// TEST 14: Short position (negative quantity)
|
||||
[Fact]
|
||||
public void ConvertPosition_WithShortPosition_ShouldHandleNegativeQuantity()
|
||||
{
|
||||
// Input: quantity=-1
|
||||
// Expected: Quantity < 0
|
||||
}
|
||||
|
||||
// TEST 15: Flat position (zero quantity)
|
||||
[Fact]
|
||||
public void ConvertPosition_WithFlatPosition_ShouldHandleZeroQuantity()
|
||||
{
|
||||
// Input: quantity=0, avgPrice=0
|
||||
// Expected: Creates valid flat position
|
||||
}
|
||||
|
||||
// TEST 16: Invalid symbol
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void ConvertPosition_WithInvalidSymbol_ShouldThrowArgumentException(string symbol)
|
||||
{
|
||||
// Expected: ArgumentException with parameter "symbol"
|
||||
}
|
||||
|
||||
// TEST 17: Negative unrealized P&L (losing position)
|
||||
[Fact]
|
||||
public void ConvertPosition_WithNegativeUnrealizedPnL_ShouldHandleCorrectly()
|
||||
{
|
||||
// Input: unrealizedPnL=-350.25
|
||||
// Expected: UnrealizedPnL property is negative
|
||||
}
|
||||
```
|
||||
|
||||
#### 4. ConvertSession Tests (4 tests)
|
||||
|
||||
```csharp
|
||||
// TEST 18: RTH session
|
||||
[Fact]
|
||||
public void ConvertSession_WithRTHSession_ShouldCreateMarketSession()
|
||||
{
|
||||
// Input: start=09:30, end=16:00, isRth=true, name="RTH"
|
||||
// Expected: IsRth=true
|
||||
}
|
||||
|
||||
// TEST 19: ETH session
|
||||
[Fact]
|
||||
public void ConvertSession_WithETHSession_ShouldCreateMarketSession()
|
||||
{
|
||||
// Input: start=18:00, end=next day 09:30, isRth=false, name="ETH"
|
||||
// Expected: IsRth=false, handles overnight session
|
||||
}
|
||||
|
||||
// TEST 20: Invalid session name
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void ConvertSession_WithInvalidName_ShouldThrowArgumentException(string name)
|
||||
{
|
||||
// Expected: ArgumentException with parameter "sessionName"
|
||||
}
|
||||
|
||||
// TEST 21: End before start (invalid range)
|
||||
[Fact]
|
||||
public void ConvertSession_WithEndBeforeStart_ShouldThrowArgumentException()
|
||||
{
|
||||
// Input: start=16:00, end=09:30
|
||||
// Expected: ArgumentException with parameter "sessionEnd"
|
||||
}
|
||||
```
|
||||
|
||||
#### 5. ConvertContext Tests (6 tests)
|
||||
|
||||
```csharp
|
||||
// TEST 22: Valid context with all components
|
||||
[Fact]
|
||||
public void ConvertContext_WithValidInputs_ShouldCreateStrategyContext()
|
||||
{
|
||||
// Input: All valid Position, Account, Session, CustomData with 2 entries
|
||||
// Expected: All properties populated, CustomData contains both entries
|
||||
}
|
||||
|
||||
// TEST 23: Null custom data
|
||||
[Fact]
|
||||
public void ConvertContext_WithNullCustomData_ShouldCreateEmptyDictionary()
|
||||
{
|
||||
// Input: customData=null
|
||||
// Expected: CustomData is non-null empty dictionary
|
||||
}
|
||||
|
||||
// TEST 24: Invalid symbol
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void ConvertContext_WithInvalidSymbol_ShouldThrowArgumentException(string symbol)
|
||||
{
|
||||
// Expected: ArgumentException with parameter "symbol"
|
||||
}
|
||||
|
||||
// TEST 25: Null position
|
||||
[Fact]
|
||||
public void ConvertContext_WithNullPosition_ShouldThrowArgumentNullException()
|
||||
{
|
||||
// Expected: ArgumentNullException with parameter "currentPosition"
|
||||
}
|
||||
|
||||
// TEST 26: Null account
|
||||
[Fact]
|
||||
public void ConvertContext_WithNullAccount_ShouldThrowArgumentNullException()
|
||||
{
|
||||
// Expected: ArgumentNullException with parameter "account"
|
||||
}
|
||||
|
||||
// TEST 27: Null session
|
||||
[Fact]
|
||||
public void ConvertContext_WithNullSession_ShouldThrowArgumentNullException()
|
||||
{
|
||||
// Expected: ArgumentNullException with parameter "session"
|
||||
}
|
||||
```
|
||||
|
||||
### Implementation Notes
|
||||
|
||||
**Framework:**
|
||||
- Use xUnit
|
||||
- Use FluentAssertions for readable assertions
|
||||
- Follow existing test patterns in `tests/NT8.Core.Tests`
|
||||
|
||||
**File Structure:**
|
||||
```csharp
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Xunit;
|
||||
using FluentAssertions;
|
||||
using NT8.Adapters.NinjaTrader;
|
||||
using NT8.Core.Common.Models;
|
||||
|
||||
namespace NT8.Core.Tests.Adapters
|
||||
{
|
||||
/// <summary>
|
||||
/// Unit tests for NT8DataConverter
|
||||
/// </summary>
|
||||
public class NT8DataConverterTests
|
||||
{
|
||||
// All 27 tests here
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Success Criteria:**
|
||||
- [ ] All 27 tests implemented
|
||||
- [ ] All tests pass
|
||||
- [ ] Zero warnings
|
||||
- [ ] Code coverage >95% for NT8DataConverter
|
||||
- [ ] Follows existing test patterns
|
||||
|
||||
---
|
||||
|
||||
## 📋 Task 2: NT8ExecutionAdapter Implementation (2-3 hours)
|
||||
|
||||
### Overview
|
||||
Create the adapter that handles REAL order submission to NinjaTrader 8.
|
||||
|
||||
### Location
|
||||
**Create:** `src/NT8.Adapters/NinjaTrader/NT8ExecutionAdapter.cs`
|
||||
**Create:** `tests/NT8.Core.Tests/Adapters/NT8ExecutionAdapterTests.cs`
|
||||
|
||||
### NT8ExecutionAdapter Specification
|
||||
|
||||
#### Class Structure
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using NT8.Core.Common.Models;
|
||||
using NT8.Core.OMS;
|
||||
|
||||
namespace NT8.Adapters.NinjaTrader
|
||||
{
|
||||
/// <summary>
|
||||
/// Adapter for executing orders through NinjaTrader 8 platform.
|
||||
/// Bridges SDK order requests to NT8 order submission and handles callbacks.
|
||||
/// Thread-safe for concurrent NT8 callbacks.
|
||||
/// </summary>
|
||||
public class NT8ExecutionAdapter
|
||||
{
|
||||
private readonly object _lock = new object();
|
||||
private readonly Dictionary<string, OrderTrackingInfo> _orderTracking;
|
||||
private readonly Dictionary<string, string> _nt8ToSdkOrderMap;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new NT8 execution adapter.
|
||||
/// </summary>
|
||||
public NT8ExecutionAdapter()
|
||||
{
|
||||
_orderTracking = new Dictionary<string, OrderTrackingInfo>();
|
||||
_nt8ToSdkOrderMap = new Dictionary<string, string>();
|
||||
}
|
||||
|
||||
// Methods defined below...
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Internal class for tracking order state
|
||||
/// </summary>
|
||||
internal class OrderTrackingInfo
|
||||
{
|
||||
public string SdkOrderId { get; set; }
|
||||
public string Nt8OrderId { get; set; }
|
||||
public OrderRequest OriginalRequest { get; set; }
|
||||
public OrderState CurrentState { get; set; }
|
||||
public int FilledQuantity { get; set; }
|
||||
public double AverageFillPrice { get; set; }
|
||||
public DateTime LastUpdate { get; set; }
|
||||
public string ErrorMessage { get; set; }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Method 1: SubmitOrder
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Submit an order to NinjaTrader 8.
|
||||
/// NOTE: This method accepts primitive parameters instead of NT8 Strategy object
|
||||
/// to maintain testability and avoid NT8 DLL dependencies in core adapter.
|
||||
/// The actual NT8StrategyBase will call NT8 methods and pass results here.
|
||||
/// </summary>
|
||||
/// <param name="request">SDK order request</param>
|
||||
/// <param name="sdkOrderId">Unique SDK order ID</param>
|
||||
/// <returns>Tracking info for the submitted order</returns>
|
||||
/// <exception cref="ArgumentNullException">If request or orderId is null</exception>
|
||||
/// <exception cref="InvalidOperationException">If order already exists</exception>
|
||||
public OrderTrackingInfo SubmitOrder(OrderRequest request, string sdkOrderId)
|
||||
{
|
||||
if (request == null)
|
||||
throw new ArgumentNullException("request");
|
||||
if (string.IsNullOrWhiteSpace(sdkOrderId))
|
||||
throw new ArgumentNullException("sdkOrderId");
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
// Check if order already tracked
|
||||
if (_orderTracking.ContainsKey(sdkOrderId))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
string.Format("Order {0} already exists", sdkOrderId));
|
||||
}
|
||||
|
||||
// Create tracking info
|
||||
var trackingInfo = new OrderTrackingInfo
|
||||
{
|
||||
SdkOrderId = sdkOrderId,
|
||||
Nt8OrderId = null, // Will be set by NT8 callback
|
||||
OriginalRequest = request,
|
||||
CurrentState = OrderState.Pending,
|
||||
FilledQuantity = 0,
|
||||
AverageFillPrice = 0.0,
|
||||
LastUpdate = DateTime.UtcNow,
|
||||
ErrorMessage = null
|
||||
};
|
||||
|
||||
_orderTracking[sdkOrderId] = trackingInfo;
|
||||
|
||||
// NOTE: Actual NT8 submission happens in NT8StrategyBase
|
||||
// This adapter only tracks state
|
||||
|
||||
return trackingInfo;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Method 2: ProcessOrderUpdate
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Process order update callback from NinjaTrader 8.
|
||||
/// Called by NT8StrategyBase.OnOrderUpdate().
|
||||
/// </summary>
|
||||
/// <param name="nt8OrderId">NT8's order ID</param>
|
||||
/// <param name="sdkOrderId">SDK's order ID (from order name/tag)</param>
|
||||
/// <param name="orderState">NT8 order state</param>
|
||||
/// <param name="filled">Filled quantity</param>
|
||||
/// <param name="averageFillPrice">Average fill price</param>
|
||||
/// <param name="errorCode">Error code if rejected</param>
|
||||
/// <param name="errorMessage">Error message if rejected</param>
|
||||
public void ProcessOrderUpdate(
|
||||
string nt8OrderId,
|
||||
string sdkOrderId,
|
||||
string orderState,
|
||||
int filled,
|
||||
double averageFillPrice,
|
||||
int errorCode,
|
||||
string errorMessage)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(sdkOrderId))
|
||||
return; // Ignore orders not from SDK
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_orderTracking.ContainsKey(sdkOrderId))
|
||||
{
|
||||
// Order not tracked, ignore
|
||||
return;
|
||||
}
|
||||
|
||||
var info = _orderTracking[sdkOrderId];
|
||||
|
||||
// Map NT8 order ID
|
||||
if (!string.IsNullOrWhiteSpace(nt8OrderId) && info.Nt8OrderId == null)
|
||||
{
|
||||
info.Nt8OrderId = nt8OrderId;
|
||||
_nt8ToSdkOrderMap[nt8OrderId] = sdkOrderId;
|
||||
}
|
||||
|
||||
// Update state
|
||||
info.CurrentState = MapNT8OrderState(orderState);
|
||||
info.FilledQuantity = filled;
|
||||
info.AverageFillPrice = averageFillPrice;
|
||||
info.LastUpdate = DateTime.UtcNow;
|
||||
|
||||
// Handle errors
|
||||
if (errorCode != 0 && !string.IsNullOrWhiteSpace(errorMessage))
|
||||
{
|
||||
info.ErrorMessage = string.Format("[{0}] {1}", errorCode, errorMessage);
|
||||
info.CurrentState = OrderState.Rejected;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Method 3: ProcessExecution
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Process execution (fill) callback from NinjaTrader 8.
|
||||
/// Called by NT8StrategyBase.OnExecutionUpdate().
|
||||
/// </summary>
|
||||
/// <param name="nt8OrderId">NT8 order ID</param>
|
||||
/// <param name="executionId">NT8 execution ID</param>
|
||||
/// <param name="price">Fill price</param>
|
||||
/// <param name="quantity">Fill quantity</param>
|
||||
/// <param name="time">Execution time</param>
|
||||
public void ProcessExecution(
|
||||
string nt8OrderId,
|
||||
string executionId,
|
||||
double price,
|
||||
int quantity,
|
||||
DateTime time)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(nt8OrderId))
|
||||
return;
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
// Map NT8 order ID to SDK order ID
|
||||
if (!_nt8ToSdkOrderMap.ContainsKey(nt8OrderId))
|
||||
return; // Not our order
|
||||
|
||||
var sdkOrderId = _nt8ToSdkOrderMap[nt8OrderId];
|
||||
if (!_orderTracking.ContainsKey(sdkOrderId))
|
||||
return;
|
||||
|
||||
var info = _orderTracking[sdkOrderId];
|
||||
|
||||
// Update fill info
|
||||
// Note: NT8 may send multiple execution callbacks for partial fills
|
||||
// We track cumulative filled quantity via ProcessOrderUpdate
|
||||
|
||||
info.LastUpdate = time;
|
||||
|
||||
// Update state based on filled quantity
|
||||
if (info.FilledQuantity >= info.OriginalRequest.Quantity)
|
||||
{
|
||||
info.CurrentState = OrderState.Filled;
|
||||
}
|
||||
else if (info.FilledQuantity > 0)
|
||||
{
|
||||
info.CurrentState = OrderState.PartiallyFilled;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Method 4: CancelOrder
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Request to cancel an order.
|
||||
/// NOTE: Actual cancellation happens in NT8StrategyBase via CancelOrder().
|
||||
/// This method validates and marks order for cancellation.
|
||||
/// </summary>
|
||||
/// <param name="sdkOrderId">SDK order ID to cancel</param>
|
||||
/// <returns>True if cancel request accepted, false if order can't be cancelled</returns>
|
||||
public bool CancelOrder(string sdkOrderId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(sdkOrderId))
|
||||
throw new ArgumentNullException("sdkOrderId");
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_orderTracking.ContainsKey(sdkOrderId))
|
||||
return false; // Order not found
|
||||
|
||||
var info = _orderTracking[sdkOrderId];
|
||||
|
||||
// Check if order is in cancellable state
|
||||
if (info.CurrentState == OrderState.Filled ||
|
||||
info.CurrentState == OrderState.Cancelled ||
|
||||
info.CurrentState == OrderState.Rejected)
|
||||
{
|
||||
return false; // Already in terminal state
|
||||
}
|
||||
|
||||
// Mark as pending cancellation
|
||||
// Actual state change happens in ProcessOrderUpdate callback
|
||||
info.LastUpdate = DateTime.UtcNow;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Method 5: GetOrderStatus
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Get current status of an order.
|
||||
/// </summary>
|
||||
/// <param name="sdkOrderId">SDK order ID</param>
|
||||
/// <returns>Order status or null if not found</returns>
|
||||
public OrderStatus GetOrderStatus(string sdkOrderId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(sdkOrderId))
|
||||
return null;
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_orderTracking.ContainsKey(sdkOrderId))
|
||||
return null;
|
||||
|
||||
var info = _orderTracking[sdkOrderId];
|
||||
|
||||
return new OrderStatus(
|
||||
orderId: info.SdkOrderId,
|
||||
state: info.CurrentState,
|
||||
symbol: info.OriginalRequest.Symbol,
|
||||
side: info.OriginalRequest.Side,
|
||||
quantity: info.OriginalRequest.Quantity,
|
||||
type: info.OriginalRequest.Type,
|
||||
filled: info.FilledQuantity,
|
||||
averageFillPrice: info.FilledQuantity > 0 ? (double?)info.AverageFillPrice : null,
|
||||
message: info.ErrorMessage,
|
||||
timestamp: info.LastUpdate
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Helper Method: MapNT8OrderState
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Maps NinjaTrader 8 order state strings to SDK OrderState enum.
|
||||
/// </summary>
|
||||
/// <param name="nt8State">NT8 order state as string</param>
|
||||
/// <returns>Mapped SDK OrderState</returns>
|
||||
private OrderState MapNT8OrderState(string nt8State)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(nt8State))
|
||||
return OrderState.Unknown;
|
||||
|
||||
// NT8 order states: https://ninjatrader.com/support/helpGuides/nt8/?orderstate.htm
|
||||
switch (nt8State.ToUpperInvariant())
|
||||
{
|
||||
case "ACCEPTED":
|
||||
case "WORKING":
|
||||
return OrderState.Working;
|
||||
|
||||
case "FILLED":
|
||||
return OrderState.Filled;
|
||||
|
||||
case "PARTFILLED":
|
||||
case "PARTIALLYFILLED":
|
||||
return OrderState.PartiallyFilled;
|
||||
|
||||
case "CANCELLED":
|
||||
case "CANCELED":
|
||||
return OrderState.Cancelled;
|
||||
|
||||
case "REJECTED":
|
||||
return OrderState.Rejected;
|
||||
|
||||
case "PENDINGCANCEL":
|
||||
return OrderState.Working; // Still working until cancelled
|
||||
|
||||
case "PENDINGCHANGE":
|
||||
case "PENDINGSUBMIT":
|
||||
return OrderState.Pending;
|
||||
|
||||
default:
|
||||
return OrderState.Unknown;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Unit Tests for NT8ExecutionAdapter
|
||||
|
||||
**Create:** `tests/NT8.Core.Tests/Adapters/NT8ExecutionAdapterTests.cs`
|
||||
|
||||
**Test Count:** 15 tests minimum
|
||||
|
||||
```csharp
|
||||
public class NT8ExecutionAdapterTests
|
||||
{
|
||||
// TEST 1: Submit valid order
|
||||
[Fact]
|
||||
public void SubmitOrder_WithValidRequest_ShouldCreateTrackingInfo()
|
||||
|
||||
// TEST 2: Submit duplicate order
|
||||
[Fact]
|
||||
public void SubmitOrder_WithDuplicateOrderId_ShouldThrowInvalidOperationException()
|
||||
|
||||
// TEST 3: Submit with null request
|
||||
[Fact]
|
||||
public void SubmitOrder_WithNullRequest_ShouldThrowArgumentNullException()
|
||||
|
||||
// TEST 4: Process order update - Working state
|
||||
[Fact]
|
||||
public void ProcessOrderUpdate_WithWorkingState_ShouldUpdateState()
|
||||
|
||||
// TEST 5: Process order update - Filled state
|
||||
[Fact]
|
||||
public void ProcessOrderUpdate_WithFilledState_ShouldMarkFilled()
|
||||
|
||||
// TEST 6: Process order update - Rejected with error
|
||||
[Fact]
|
||||
public void ProcessOrderUpdate_WithRejection_ShouldSetErrorMessage()
|
||||
|
||||
// TEST 7: Process execution - Full fill
|
||||
[Fact]
|
||||
public void ProcessExecution_WithFullFill_ShouldMarkFilled()
|
||||
|
||||
// TEST 8: Process execution - Partial fill
|
||||
[Fact]
|
||||
public void ProcessExecution_WithPartialFill_ShouldMarkPartiallyFilled()
|
||||
|
||||
// TEST 9: Cancel order - Valid
|
||||
[Fact]
|
||||
public void CancelOrder_WithWorkingOrder_ShouldReturnTrue()
|
||||
|
||||
// TEST 10: Cancel order - Already filled
|
||||
[Fact]
|
||||
public void CancelOrder_WithFilledOrder_ShouldReturnFalse()
|
||||
|
||||
// TEST 11: Get order status - Exists
|
||||
[Fact]
|
||||
public void GetOrderStatus_WithExistingOrder_ShouldReturnStatus()
|
||||
|
||||
// TEST 12: Get order status - Not found
|
||||
[Fact]
|
||||
public void GetOrderStatus_WithNonExistentOrder_ShouldReturnNull()
|
||||
|
||||
// TEST 13: NT8 order state mapping
|
||||
[Theory]
|
||||
[InlineData("ACCEPTED", OrderState.Working)]
|
||||
[InlineData("FILLED", OrderState.Filled)]
|
||||
[InlineData("CANCELLED", OrderState.Cancelled)]
|
||||
[InlineData("REJECTED", OrderState.Rejected)]
|
||||
public void MapNT8OrderState_WithKnownStates_ShouldMapCorrectly(string nt8State, OrderState expected)
|
||||
|
||||
// TEST 14: Thread safety - Concurrent submissions
|
||||
[Fact]
|
||||
public void SubmitOrder_WithConcurrentCalls_ShouldBeThreadSafe()
|
||||
|
||||
// TEST 15: Multiple executions for same order
|
||||
[Fact]
|
||||
public void ProcessExecution_WithMultipleCallsForSameOrder_ShouldAccumulate()
|
||||
}
|
||||
```
|
||||
|
||||
### Success Criteria
|
||||
|
||||
**For NT8ExecutionAdapter:**
|
||||
- [ ] All public methods implemented
|
||||
- [ ] Thread-safe with lock protection
|
||||
- [ ] Comprehensive XML documentation
|
||||
- [ ] C# 5.0 compliant (no modern syntax)
|
||||
- [ ] Zero build warnings
|
||||
|
||||
**For Tests:**
|
||||
- [ ] All 15 tests implemented
|
||||
- [ ] All tests pass
|
||||
- [ ] Code coverage >90% for NT8ExecutionAdapter
|
||||
- [ ] Thread safety validated
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Implementation Workflow
|
||||
|
||||
### Step 1: Create Test File (30 min)
|
||||
1. Create `tests/NT8.Core.Tests/Adapters/` directory
|
||||
2. Create `NT8DataConverterTests.cs`
|
||||
3. Implement all 27 tests
|
||||
4. Run tests - should all PASS (code already exists)
|
||||
|
||||
### Step 2: Verify Test Coverage (15 min)
|
||||
```bash
|
||||
dotnet test --collect:"XPlat Code Coverage"
|
||||
# Verify >95% coverage for NT8DataConverter
|
||||
```
|
||||
|
||||
### Step 3: Create NT8ExecutionAdapter (2 hours)
|
||||
1. Create `src/NT8.Adapters/NinjaTrader/NT8ExecutionAdapter.cs`
|
||||
2. Implement all methods per specification
|
||||
3. Add XML documentation
|
||||
4. Verify C# 5.0 compliance
|
||||
|
||||
### Step 4: Create Execution Adapter Tests (1 hour)
|
||||
1. Create `tests/NT8.Core.Tests/Adapters/NT8ExecutionAdapterTests.cs`
|
||||
2. Implement all 15 tests
|
||||
3. Run tests - should all PASS
|
||||
|
||||
### Step 5: Build & Verify (15 min)
|
||||
```bash
|
||||
dotnet build --configuration Release
|
||||
dotnet test --configuration Release
|
||||
.\verify-build.bat
|
||||
```
|
||||
|
||||
### Step 6: Git Commit
|
||||
```bash
|
||||
git add tests/NT8.Core.Tests/Adapters/
|
||||
git add src/NT8.Adapters/NinjaTrader/NT8ExecutionAdapter.cs
|
||||
git commit -m "feat: Add NT8 adapter tests and execution adapter
|
||||
|
||||
- Added 27 unit tests for NT8DataConverter (>95% coverage)
|
||||
- Implemented NT8ExecutionAdapter with order tracking
|
||||
- Added 15 unit tests for NT8ExecutionAdapter (>90% coverage)
|
||||
- Thread-safe order state management
|
||||
- NT8 order state mapping
|
||||
- C# 5.0 compliant
|
||||
|
||||
Phase A complete: Foundation adapters ready for NT8 integration"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 Deliverables Checklist
|
||||
|
||||
- [ ] `tests/NT8.Core.Tests/Adapters/NT8DataConverterTests.cs` (27 tests)
|
||||
- [ ] `src/NT8.Adapters/NinjaTrader/NT8ExecutionAdapter.cs` (full implementation)
|
||||
- [ ] `tests/NT8.Core.Tests/Adapters/NT8ExecutionAdapterTests.cs` (15 tests)
|
||||
- [ ] All 42 new tests passing
|
||||
- [ ] All 240+ existing tests still passing
|
||||
- [ ] Zero build warnings
|
||||
- [ ] Code coverage: >95% for DataConverter, >90% for ExecutionAdapter
|
||||
- [ ] Git commit with clear message
|
||||
|
||||
---
|
||||
|
||||
## 🚨 Important Constraints
|
||||
|
||||
1. **C# 5.0 Only** - No:
|
||||
- `async/await`
|
||||
- String interpolation `$""`
|
||||
- Expression-bodied members `=>`
|
||||
- Pattern matching
|
||||
- Tuples
|
||||
- Use `string.Format()` instead of `$""`
|
||||
|
||||
2. **Thread Safety** - All shared state must use `lock (_lock)`
|
||||
|
||||
3. **Defensive Programming** - Validate all inputs, null checks
|
||||
|
||||
4. **XML Documentation** - All public members must have /// comments
|
||||
|
||||
5. **Test Patterns** - Follow existing test conventions in `tests/NT8.Core.Tests`
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Success Metrics
|
||||
|
||||
**Definition of Done:**
|
||||
- ✅ All 42 tests passing
|
||||
- ✅ All existing 240+ tests still passing
|
||||
- ✅ Build succeeds with zero warnings
|
||||
- ✅ Code coverage targets met
|
||||
- ✅ Thread safety verified
|
||||
- ✅ C# 5.0 compliant
|
||||
- ✅ Committed to Git
|
||||
|
||||
**Time Target:** 4-5 hours total
|
||||
|
||||
---
|
||||
|
||||
**READY FOR KILOCODE EXECUTION IN CODE MODE** ✅
|
||||
1293
docs/archive/phase-specs/PHASE_B_SPECIFICATION.md
Normal file
1293
docs/archive/phase-specs/PHASE_B_SPECIFICATION.md
Normal file
File diff suppressed because it is too large
Load Diff
1134
docs/archive/phase-specs/PHASE_C_SPECIFICATION.md
Normal file
1134
docs/archive/phase-specs/PHASE_C_SPECIFICATION.md
Normal file
File diff suppressed because it is too large
Load Diff
767
docs/archive/phase-specs/Phase3_Implementation_Guide.md
Normal file
767
docs/archive/phase-specs/Phase3_Implementation_Guide.md
Normal file
@@ -0,0 +1,767 @@
|
||||
# Phase 3: Market Microstructure & Execution - Implementation Guide
|
||||
|
||||
**Estimated Time:** 3-4 hours
|
||||
**Complexity:** Medium-High
|
||||
**Dependencies:** Phase 2 Complete ✅
|
||||
|
||||
---
|
||||
|
||||
## Implementation Overview
|
||||
|
||||
This phase adds professional-grade execution capabilities with market awareness, advanced order types, execution quality tracking, and intelligent order routing. We're building the "HOW to trade" layer on top of Phase 2's "WHAT to trade" foundation.
|
||||
|
||||
---
|
||||
|
||||
## Phase A: Market Microstructure Awareness (45 minutes)
|
||||
|
||||
### Task A1: Create MarketMicrostructureModels.cs
|
||||
**Location:** `src/NT8.Core/MarketData/MarketMicrostructureModels.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- `SpreadInfo` record - Bid-ask spread tracking
|
||||
- `LiquidityMetrics` record - Order book depth analysis
|
||||
- `SessionInfo` record - RTH vs ETH session data
|
||||
- `ContractRollInfo` record - Roll detection data
|
||||
- `LiquidityScore` enum - Poor/Fair/Good/Excellent
|
||||
- `TradingSession` enum - PreMarket/RTH/ETH/Closed
|
||||
|
||||
**Key Requirements:**
|
||||
- C# 5.0 syntax only
|
||||
- Thread-safe value types (records)
|
||||
- XML documentation
|
||||
- Proper validation
|
||||
|
||||
---
|
||||
|
||||
### Task A2: Create LiquidityMonitor.cs
|
||||
**Location:** `src/NT8.Core/MarketData/LiquidityMonitor.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Track bid-ask spread in real-time
|
||||
- Calculate liquidity score by symbol
|
||||
- Monitor order book depth
|
||||
- Detect liquidity deterioration
|
||||
- Session-aware monitoring (RTH vs ETH)
|
||||
|
||||
**Key Features:**
|
||||
- Rolling window for spread tracking (last 100 ticks)
|
||||
- Liquidity scoring algorithm
|
||||
- Alert thresholds for poor liquidity
|
||||
- Thread-safe with proper locking
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public void UpdateSpread(string symbol, double bid, double ask, long volume);
|
||||
public LiquidityMetrics GetLiquidityMetrics(string symbol);
|
||||
public LiquidityScore CalculateLiquidityScore(string symbol);
|
||||
public bool IsLiquidityAcceptable(string symbol, double threshold);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task A3: Create SessionManager.cs
|
||||
**Location:** `src/NT8.Core/MarketData/SessionManager.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Track current trading session (RTH/ETH)
|
||||
- Session start/end times by symbol
|
||||
- Holiday calendar awareness
|
||||
- Contract roll detection
|
||||
|
||||
**Key Features:**
|
||||
- Symbol-specific session times
|
||||
- Timezone handling (EST for US futures)
|
||||
- Holiday detection
|
||||
- Roll date tracking for futures
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public SessionInfo GetCurrentSession(string symbol, DateTime time);
|
||||
public bool IsRegularTradingHours(string symbol, DateTime time);
|
||||
public bool IsContractRolling(string symbol, DateTime time);
|
||||
public DateTime GetNextSessionStart(string symbol);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase B: Advanced Order Types (60 minutes)
|
||||
|
||||
### Task B1: Extend OrderModels.cs
|
||||
**Location:** `src/NT8.Core/OMS/OrderModels.cs`
|
||||
|
||||
**Add to existing file:**
|
||||
- `LimitOrderRequest` record
|
||||
- `StopOrderRequest` record
|
||||
- `StopLimitOrderRequest` record
|
||||
- `MITOrderRequest` record (Market-If-Touched)
|
||||
- `TrailingStopConfig` record
|
||||
- `OrderTypeParameters` record
|
||||
|
||||
**Order Type Specifications:**
|
||||
|
||||
**Limit Order:**
|
||||
```csharp
|
||||
public record LimitOrderRequest(
|
||||
string Symbol,
|
||||
OrderSide Side,
|
||||
int Quantity,
|
||||
double LimitPrice,
|
||||
TimeInForce Tif
|
||||
) : OrderRequest;
|
||||
```
|
||||
|
||||
**Stop Order:**
|
||||
```csharp
|
||||
public record StopOrderRequest(
|
||||
string Symbol,
|
||||
OrderSide Side,
|
||||
int Quantity,
|
||||
double StopPrice,
|
||||
TimeInForce Tif
|
||||
) : OrderRequest;
|
||||
```
|
||||
|
||||
**Stop-Limit Order:**
|
||||
```csharp
|
||||
public record StopLimitOrderRequest(
|
||||
string Symbol,
|
||||
OrderSide Side,
|
||||
int Quantity,
|
||||
double StopPrice,
|
||||
double LimitPrice,
|
||||
TimeInForce Tif
|
||||
) : OrderRequest;
|
||||
```
|
||||
|
||||
**MIT Order:**
|
||||
```csharp
|
||||
public record MITOrderRequest(
|
||||
string Symbol,
|
||||
OrderSide Side,
|
||||
int Quantity,
|
||||
double TriggerPrice,
|
||||
TimeInForce Tif
|
||||
) : OrderRequest;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task B2: Create OrderTypeValidator.cs
|
||||
**Location:** `src/NT8.Core/OMS/OrderTypeValidator.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Validate order type parameters
|
||||
- Check price relationships (stop vs limit)
|
||||
- Verify order side consistency
|
||||
- Symbol-specific validation rules
|
||||
|
||||
**Validation Rules:**
|
||||
- Limit buy: limit price < market price
|
||||
- Limit sell: limit price > market price
|
||||
- Stop buy: stop price > market price
|
||||
- Stop sell: stop price < market price
|
||||
- Stop-Limit: stop and limit relationship validation
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public ValidationResult ValidateLimitOrder(LimitOrderRequest request, double marketPrice);
|
||||
public ValidationResult ValidateStopOrder(StopOrderRequest request, double marketPrice);
|
||||
public ValidationResult ValidateStopLimitOrder(StopLimitOrderRequest request, double marketPrice);
|
||||
public ValidationResult ValidateMITOrder(MITOrderRequest request, double marketPrice);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task B3: Update BasicOrderManager.cs
|
||||
**Location:** `src/NT8.Core/OMS/BasicOrderManager.cs`
|
||||
|
||||
**Add methods (don't modify existing):**
|
||||
```csharp
|
||||
public async Task<string> SubmitLimitOrderAsync(LimitOrderRequest request);
|
||||
public async Task<string> SubmitStopOrderAsync(StopOrderRequest request);
|
||||
public async Task<string> SubmitStopLimitOrderAsync(StopLimitOrderRequest request);
|
||||
public async Task<string> SubmitMITOrderAsync(MITOrderRequest request);
|
||||
```
|
||||
|
||||
**Implementation:**
|
||||
- Validate order type parameters
|
||||
- Convert to base OrderRequest
|
||||
- Submit through existing infrastructure
|
||||
- Track order type in metadata
|
||||
|
||||
---
|
||||
|
||||
## Phase C: Execution Quality Tracking (50 minutes)
|
||||
|
||||
### Task C1: Create ExecutionModels.cs
|
||||
**Location:** `src/NT8.Core/Execution/ExecutionModels.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- `ExecutionMetrics` record - Per-order execution data
|
||||
- `SlippageInfo` record - Price slippage tracking
|
||||
- `ExecutionTiming` record - Latency breakdown
|
||||
- `ExecutionQuality` enum - Excellent/Good/Fair/Poor
|
||||
- `SlippageType` enum - Positive/Negative/Zero
|
||||
|
||||
**ExecutionMetrics:**
|
||||
```csharp
|
||||
public record ExecutionMetrics(
|
||||
string OrderId,
|
||||
DateTime IntentTime,
|
||||
DateTime SubmitTime,
|
||||
DateTime FillTime,
|
||||
double IntendedPrice,
|
||||
double FillPrice,
|
||||
double Slippage,
|
||||
SlippageType SlippageType,
|
||||
TimeSpan SubmitLatency,
|
||||
TimeSpan FillLatency,
|
||||
ExecutionQuality Quality
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task C2: Create ExecutionQualityTracker.cs
|
||||
**Location:** `src/NT8.Core/Execution/ExecutionQualityTracker.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Track every order execution
|
||||
- Calculate slippage (intended vs actual)
|
||||
- Measure execution latency
|
||||
- Score execution quality
|
||||
- Maintain execution history
|
||||
|
||||
**Key Features:**
|
||||
- Per-symbol execution statistics
|
||||
- Rolling averages (last 100 executions)
|
||||
- Quality scoring algorithm
|
||||
- Alert on poor execution quality
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public void RecordExecution(string orderId, StrategyIntent intent, OrderFill fill);
|
||||
public ExecutionMetrics GetExecutionMetrics(string orderId);
|
||||
public ExecutionStatistics GetSymbolStatistics(string symbol);
|
||||
public double GetAverageSlippage(string symbol);
|
||||
public bool IsExecutionQualityAcceptable(string symbol);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task C3: Create SlippageCalculator.cs
|
||||
**Location:** `src/NT8.Core/Execution/SlippageCalculator.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Calculate price slippage
|
||||
- Determine slippage type (favorable/unfavorable)
|
||||
- Normalize slippage by symbol (tick-based)
|
||||
- Slippage impact on P&L
|
||||
|
||||
**Slippage Formula:**
|
||||
```
|
||||
Market Order:
|
||||
Slippage = FillPrice - MarketPriceAtSubmit
|
||||
|
||||
Limit Order:
|
||||
Slippage = FillPrice - LimitPrice (if better = favorable)
|
||||
|
||||
Slippage in Ticks = Slippage / TickSize
|
||||
Slippage Cost = Slippage * Quantity * TickValue
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public double CalculateSlippage(OrderType type, double intendedPrice, double fillPrice);
|
||||
public SlippageType ClassifySlippage(double slippage, OrderSide side);
|
||||
public int SlippageInTicks(double slippage, double tickSize);
|
||||
public double SlippageImpact(double slippage, int quantity, double tickValue);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase D: Smart Order Routing (45 minutes)
|
||||
|
||||
### Task D1: Create OrderRoutingModels.cs
|
||||
**Location:** `src/NT8.Core/Execution/OrderRoutingModels.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- `RoutingDecision` record - Route selection result
|
||||
- `OrderDuplicateCheck` record - Duplicate detection data
|
||||
- `CircuitBreakerState` record - Circuit breaker status
|
||||
- `RoutingStrategy` enum - Direct/Smart/Fallback
|
||||
|
||||
---
|
||||
|
||||
### Task D2: Create DuplicateOrderDetector.cs
|
||||
**Location:** `src/NT8.Core/Execution/DuplicateOrderDetector.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Detect duplicate order submissions
|
||||
- Time-based duplicate window (5 seconds)
|
||||
- Symbol + side + quantity matching
|
||||
- Prevent accidental double-entry
|
||||
|
||||
**Detection Logic:**
|
||||
```csharp
|
||||
IsDuplicate =
|
||||
Same symbol AND
|
||||
Same side AND
|
||||
Same quantity AND
|
||||
Within 5 seconds
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public bool IsDuplicateOrder(OrderRequest request);
|
||||
public void RecordOrderIntent(OrderRequest request);
|
||||
public void ClearOldIntents(TimeSpan maxAge);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task D3: Create ExecutionCircuitBreaker.cs
|
||||
**Location:** `src/NT8.Core/Execution/ExecutionCircuitBreaker.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Monitor execution latency
|
||||
- Detect slow execution patterns
|
||||
- Circuit breaker triggers
|
||||
- Automatic recovery
|
||||
|
||||
**Circuit Breaker States:**
|
||||
- **Closed** (normal): Orders flow normally
|
||||
- **Open** (triggered): Block new orders
|
||||
- **Half-Open** (testing): Allow limited orders
|
||||
|
||||
**Trigger Conditions:**
|
||||
- Average execution time > 5 seconds (3 consecutive)
|
||||
- Order rejection rate > 50% (last 10 orders)
|
||||
- Manual trigger via emergency command
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public void RecordExecutionTime(TimeSpan latency);
|
||||
public void RecordOrderRejection(string reason);
|
||||
public bool ShouldAllowOrder();
|
||||
public CircuitBreakerState GetState();
|
||||
public void Reset();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task D4: Create ContractRollHandler.cs
|
||||
**Location:** `src/NT8.Core/Execution/ContractRollHandler.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Detect contract roll periods
|
||||
- Switch to new contract automatically
|
||||
- Position transfer logic
|
||||
- Roll notification
|
||||
|
||||
**Key Features:**
|
||||
- Symbol-specific roll dates
|
||||
- Front month vs back month tracking
|
||||
- Position rollover planning
|
||||
- Volume-based roll detection
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public bool IsRollPeriod(string symbol, DateTime date);
|
||||
public string GetActiveContract(string baseSymbol, DateTime date);
|
||||
public RollDecision ShouldRollPosition(string symbol, Position position);
|
||||
public void InitiateRollover(string fromContract, string toContract);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase E: Stops & Targets Framework (50 minutes)
|
||||
|
||||
### Task E1: Create StopsTargetsModels.cs
|
||||
**Location:** `src/NT8.Core/Execution/StopsTargetsModels.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- `MultiLevelTargets` record - TP1, TP2, TP3 configuration
|
||||
- `TrailingStopConfig` record - Trailing stop parameters
|
||||
- `AutoBreakevenConfig` record - Auto-breakeven rules
|
||||
- `StopType` enum - Fixed/Trailing/ATR/Chandelier
|
||||
- `TargetType` enum - Fixed/RMultiple/Percent
|
||||
|
||||
**MultiLevelTargets:**
|
||||
```csharp
|
||||
public record MultiLevelTargets(
|
||||
int TP1Ticks,
|
||||
int TP1Contracts, // How many contracts to take profit
|
||||
int? TP2Ticks,
|
||||
int? TP2Contracts,
|
||||
int? TP3Ticks,
|
||||
int? TP3Contracts
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task E2: Create TrailingStopManager.cs
|
||||
**Location:** `src/NT8.Core/Execution/TrailingStopManager.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Multiple trailing stop types
|
||||
- Dynamic stop adjustment
|
||||
- Auto-breakeven logic
|
||||
- Per-position stop tracking
|
||||
|
||||
**Trailing Stop Types:**
|
||||
|
||||
**1. Fixed Trailing:**
|
||||
```
|
||||
Trail by fixed ticks from highest high (long) or lowest low (short)
|
||||
```
|
||||
|
||||
**2. ATR Trailing:**
|
||||
```
|
||||
Trail by ATR multiplier (e.g., 2 * ATR)
|
||||
```
|
||||
|
||||
**3. Chandelier:**
|
||||
```
|
||||
Trail from highest high minus ATR * multiplier
|
||||
```
|
||||
|
||||
**4. Parabolic SAR:**
|
||||
```
|
||||
Accelerating factor-based trailing
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public void StartTrailing(string orderId, Position position, TrailingStopConfig config);
|
||||
public void UpdateTrailingStop(string orderId, double currentPrice);
|
||||
public double CalculateNewStopPrice(StopType type, Position position, double marketPrice);
|
||||
public bool ShouldMoveToBreakeven(Position position, double currentPrice);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task E3: Create MultiLevelTargetManager.cs
|
||||
**Location:** `src/NT8.Core/Execution/MultiLevelTargetManager.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Manage multiple profit targets
|
||||
- Partial position closure
|
||||
- Automatic target progression
|
||||
- Scale-out logic
|
||||
|
||||
**Scale-Out Logic:**
|
||||
```
|
||||
Entry: 5 contracts
|
||||
TP1 (8 ticks): Close 2 contracts, move stop to breakeven
|
||||
TP2 (16 ticks): Close 2 contracts, trail stop
|
||||
TP3 (32 ticks): Close 1 contract (final)
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public void SetTargets(string orderId, MultiLevelTargets targets);
|
||||
public void OnTargetHit(string orderId, int targetLevel, double price);
|
||||
public int CalculateContractsToClose(int targetLevel);
|
||||
public bool ShouldAdvanceStop(int targetLevel);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task E4: Create RMultipleCalculator.cs
|
||||
**Location:** `src/NT8.Core/Execution/RMultipleCalculator.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- R-multiple based targets
|
||||
- Risk-reward ratio calculation
|
||||
- Position sizing by R
|
||||
- P&L in R terms
|
||||
|
||||
**R-Multiple Concept:**
|
||||
```
|
||||
R = Initial Risk (Stop distance × TickValue × Contracts)
|
||||
Target = Entry ± (R × Multiple)
|
||||
|
||||
Example:
|
||||
Entry: 4200, Stop: 4192 (8 ticks)
|
||||
R = 8 ticks = $100 per contract
|
||||
1R Target: 4208 (8 ticks profit)
|
||||
2R Target: 4216 (16 ticks profit)
|
||||
3R Target: 4232 (32 ticks profit)
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public double CalculateRValue(Position position, double stopPrice, double tickValue);
|
||||
public double CalculateTargetPrice(double entryPrice, double rValue, double rMultiple, OrderSide side);
|
||||
public double CalculateRMultiple(double entryPrice, double exitPrice, double rValue);
|
||||
public MultiLevelTargets CreateRBasedTargets(double entryPrice, double stopPrice, double[] rMultiples);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase F: Comprehensive Testing (60 minutes)
|
||||
|
||||
### Task F1: LiquidityMonitorTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/MarketData/LiquidityMonitorTests.cs`
|
||||
|
||||
**Test Coverage:**
|
||||
- Spread tracking accuracy
|
||||
- Liquidity score calculation
|
||||
- Session-aware monitoring
|
||||
- Thread safety with concurrent updates
|
||||
- Alert thresholds
|
||||
|
||||
**Minimum:** 15 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F2: ExecutionQualityTrackerTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Execution/ExecutionQualityTrackerTests.cs`
|
||||
|
||||
**Test Coverage:**
|
||||
- Slippage calculation accuracy
|
||||
- Execution latency tracking
|
||||
- Quality scoring logic
|
||||
- Statistics aggregation
|
||||
- Historical data retention
|
||||
|
||||
**Minimum:** 18 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F3: OrderTypeValidatorTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/OMS/OrderTypeValidatorTests.cs`
|
||||
|
||||
**Test Coverage:**
|
||||
- All order type validations
|
||||
- Price relationship checks
|
||||
- Market price boundary conditions
|
||||
- Invalid order rejection
|
||||
- Edge cases
|
||||
|
||||
**Minimum:** 20 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F4: TrailingStopManagerTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Execution/TrailingStopManagerTests.cs`
|
||||
|
||||
**Test Coverage:**
|
||||
- All trailing stop types
|
||||
- Auto-breakeven logic
|
||||
- Stop adjustment accuracy
|
||||
- Multi-position handling
|
||||
- Edge cases
|
||||
|
||||
**Minimum:** 15 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F5: MultiLevelTargetManagerTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Execution/MultiLevelTargetManagerTests.cs`
|
||||
|
||||
**Test Coverage:**
|
||||
- Scale-out logic
|
||||
- Partial closures
|
||||
- Stop advancement
|
||||
- Target progression
|
||||
- Edge cases
|
||||
|
||||
**Minimum:** 12 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F6: IntegrationTests.cs
|
||||
**Location:** `tests/NT8.Integration.Tests/Phase3IntegrationTests.cs`
|
||||
|
||||
**Test Coverage:**
|
||||
- Full execution flow: Intent → Order Type → Execution → Quality Tracking
|
||||
- Multi-level targets with trailing stops
|
||||
- Circuit breaker integration
|
||||
- Duplicate order prevention
|
||||
- Complete trade lifecycle
|
||||
|
||||
**Minimum:** 10 tests
|
||||
|
||||
---
|
||||
|
||||
## Phase G: Integration & Verification (30 minutes)
|
||||
|
||||
### Task G1: Performance Benchmarks
|
||||
**Location:** `tests/NT8.Performance.Tests/Phase3PerformanceTests.cs`
|
||||
|
||||
**Benchmarks:**
|
||||
- Order type validation: <2ms
|
||||
- Execution quality calculation: <3ms
|
||||
- Liquidity score update: <1ms
|
||||
- Trailing stop update: <2ms
|
||||
- Overall execution flow: <15ms
|
||||
|
||||
---
|
||||
|
||||
### Task G2: Build Verification
|
||||
**Command:** `.\verify-build.bat`
|
||||
|
||||
**Requirements:**
|
||||
- Zero errors
|
||||
- Zero warnings for new Phase 3 code
|
||||
- All tests passing (120+ total)
|
||||
- Coverage >80%
|
||||
|
||||
---
|
||||
|
||||
### Task G3: Documentation Update
|
||||
**Files to update:**
|
||||
- Update README.md with Phase 3 features
|
||||
- Create Phase3_Completion_Report.md
|
||||
- Update API_REFERENCE.md with new interfaces
|
||||
- Add execution examples to docs
|
||||
|
||||
---
|
||||
|
||||
## Success Criteria
|
||||
|
||||
### Code Quality
|
||||
- ✅ C# 5.0 syntax only (no C# 6+)
|
||||
- ✅ Thread-safe (locks on all shared state)
|
||||
- ✅ XML docs on all public members
|
||||
- ✅ Try-catch on all public methods
|
||||
- ✅ Structured logging throughout
|
||||
|
||||
### Testing
|
||||
- ✅ >120 total tests passing
|
||||
- ✅ >80% code coverage
|
||||
- ✅ All execution scenarios tested
|
||||
- ✅ All order types tested
|
||||
- ✅ Integration tests pass
|
||||
- ✅ Performance benchmarks met
|
||||
|
||||
### Performance
|
||||
- ✅ Order validation <2ms
|
||||
- ✅ Execution tracking <3ms
|
||||
- ✅ Liquidity update <1ms
|
||||
- ✅ Overall flow <15ms
|
||||
- ✅ No memory leaks
|
||||
|
||||
### Integration
|
||||
- ✅ Works with Phase 2 risk/sizing
|
||||
- ✅ No breaking changes
|
||||
- ✅ Clean interfaces
|
||||
- ✅ Backward compatible
|
||||
|
||||
---
|
||||
|
||||
## File Creation Checklist
|
||||
|
||||
### New Files (20):
|
||||
**MarketData (3):**
|
||||
- [ ] `src/NT8.Core/MarketData/MarketMicrostructureModels.cs`
|
||||
- [ ] `src/NT8.Core/MarketData/LiquidityMonitor.cs`
|
||||
- [ ] `src/NT8.Core/MarketData/SessionManager.cs`
|
||||
|
||||
**OMS (1):**
|
||||
- [ ] `src/NT8.Core/OMS/OrderTypeValidator.cs`
|
||||
|
||||
**Execution (10):**
|
||||
- [ ] `src/NT8.Core/Execution/ExecutionModels.cs`
|
||||
- [ ] `src/NT8.Core/Execution/ExecutionQualityTracker.cs`
|
||||
- [ ] `src/NT8.Core/Execution/SlippageCalculator.cs`
|
||||
- [ ] `src/NT8.Core/Execution/OrderRoutingModels.cs`
|
||||
- [ ] `src/NT8.Core/Execution/DuplicateOrderDetector.cs`
|
||||
- [ ] `src/NT8.Core/Execution/ExecutionCircuitBreaker.cs`
|
||||
- [ ] `src/NT8.Core/Execution/ContractRollHandler.cs`
|
||||
- [ ] `src/NT8.Core/Execution/StopsTargetsModels.cs`
|
||||
- [ ] `src/NT8.Core/Execution/TrailingStopManager.cs`
|
||||
- [ ] `src/NT8.Core/Execution/MultiLevelTargetManager.cs`
|
||||
- [ ] `src/NT8.Core/Execution/RMultipleCalculator.cs`
|
||||
|
||||
**Tests (6):**
|
||||
- [ ] `tests/NT8.Core.Tests/MarketData/LiquidityMonitorTests.cs`
|
||||
- [ ] `tests/NT8.Core.Tests/Execution/ExecutionQualityTrackerTests.cs`
|
||||
- [ ] `tests/NT8.Core.Tests/OMS/OrderTypeValidatorTests.cs`
|
||||
- [ ] `tests/NT8.Core.Tests/Execution/TrailingStopManagerTests.cs`
|
||||
- [ ] `tests/NT8.Core.Tests/Execution/MultiLevelTargetManagerTests.cs`
|
||||
- [ ] `tests/NT8.Integration.Tests/Phase3IntegrationTests.cs`
|
||||
|
||||
### Updated Files (2):
|
||||
- [ ] `src/NT8.Core/OMS/OrderModels.cs` - ADD order type records
|
||||
- [ ] `src/NT8.Core/OMS/BasicOrderManager.cs` - ADD order type methods
|
||||
|
||||
**Total:** 20 new files, 2 updated files
|
||||
|
||||
---
|
||||
|
||||
## Estimated Timeline
|
||||
|
||||
| Phase | Tasks | Time | Cumulative |
|
||||
|-------|-------|------|------------|
|
||||
| **A** | Market Microstructure | 45 min | 0:45 |
|
||||
| **B** | Advanced Order Types | 60 min | 1:45 |
|
||||
| **C** | Execution Quality | 50 min | 2:35 |
|
||||
| **D** | Smart Routing | 45 min | 3:20 |
|
||||
| **E** | Stops & Targets | 50 min | 4:10 |
|
||||
| **F** | Testing | 60 min | 5:10 |
|
||||
| **G** | Verification | 30 min | 5:40 |
|
||||
|
||||
**Total:** 5-6 hours (budget 3-4 hours for Kilocode efficiency)
|
||||
|
||||
---
|
||||
|
||||
## Critical Notes
|
||||
|
||||
### Modifications to Existing Code
|
||||
**IMPORTANT:** Only these files can be modified:
|
||||
- ✅ `src/NT8.Core/OMS/OrderModels.cs` - ADD records only
|
||||
- ✅ `src/NT8.Core/OMS/BasicOrderManager.cs` - ADD methods only
|
||||
|
||||
**FORBIDDEN:**
|
||||
- ❌ Do NOT modify interfaces
|
||||
- ❌ Do NOT modify existing method signatures
|
||||
- ❌ Do NOT change Phase 1-2 behavior
|
||||
|
||||
### Thread Safety
|
||||
Every class with shared state MUST:
|
||||
```csharp
|
||||
private readonly object _lock = new object();
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
// All shared state access
|
||||
}
|
||||
```
|
||||
|
||||
### C# 5.0 Compliance
|
||||
**Verify after each file:**
|
||||
- No `$"string {interpolation}"`
|
||||
- No `?.` or `?[` operators
|
||||
- No `=>` expression bodies
|
||||
- No inline out variables
|
||||
- Use `string.Format()` for formatting
|
||||
|
||||
---
|
||||
|
||||
## Ready to Start?
|
||||
|
||||
**Paste into Kilocode Code Mode:**
|
||||
|
||||
```
|
||||
I'm ready to implement Phase 3: Market Microstructure & Execution.
|
||||
|
||||
I will follow Phase3_Implementation_Guide.md starting with
|
||||
Task A1: Create MarketMicrostructureModels.cs
|
||||
|
||||
Please confirm you understand:
|
||||
- C# 5.0 syntax requirements
|
||||
- File modification boundaries (MarketData/Execution/OMS only)
|
||||
- Thread safety requirements (locks on all shared state)
|
||||
- No breaking changes to existing interfaces
|
||||
- Verification after each file (Ctrl+Shift+B)
|
||||
|
||||
Let's start with creating MarketMicrostructureModels.cs in src/NT8.Core/MarketData/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Phase 3 will complete your trading core!** 🚀
|
||||
900
docs/archive/phase-specs/Phase4_Implementation_Guide.md
Normal file
900
docs/archive/phase-specs/Phase4_Implementation_Guide.md
Normal file
@@ -0,0 +1,900 @@
|
||||
# Phase 4: Intelligence & Grading - Implementation Guide
|
||||
|
||||
**Estimated Time:** 4-5 hours
|
||||
**Complexity:** High
|
||||
**Dependencies:** Phase 3 Complete ✅
|
||||
|
||||
---
|
||||
|
||||
## Implementation Overview
|
||||
|
||||
Phase 4 adds the "intelligence layer" - confluence scoring, regime detection, grade-based sizing, and risk mode automation. This transforms the system from mechanical execution to intelligent trade selection.
|
||||
|
||||
**Core Concept:** Not all trades are equal. Grade them, size accordingly, and adapt risk based on conditions.
|
||||
|
||||
---
|
||||
|
||||
## Phase A: Confluence Scoring Foundation (60 minutes)
|
||||
|
||||
### Task A1: Create ConfluenceModels.cs
|
||||
**Location:** `src/NT8.Core/Intelligence/ConfluenceModels.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- `ConfluenceFactor` record - Individual factor contribution
|
||||
- `ConfluenceScore` record - Overall trade score
|
||||
- `TradeGrade` enum - A+, A, B, C, D, F
|
||||
- `FactorType` enum - Setup, Trend, Volatility, Timing, Quality, etc.
|
||||
- `FactorWeight` record - Dynamic factor weighting
|
||||
|
||||
**ConfluenceFactor:**
|
||||
```csharp
|
||||
public record ConfluenceFactor(
|
||||
FactorType Type,
|
||||
string Name,
|
||||
double Score, // 0.0 to 1.0
|
||||
double Weight, // Importance weight
|
||||
string Reason,
|
||||
Dictionary<string, object> Details
|
||||
);
|
||||
```
|
||||
|
||||
**ConfluenceScore:**
|
||||
```csharp
|
||||
public record ConfluenceScore(
|
||||
double RawScore, // 0.0 to 1.0
|
||||
double WeightedScore, // After applying weights
|
||||
TradeGrade Grade, // A+ to F
|
||||
List<ConfluenceFactor> Factors,
|
||||
DateTime CalculatedAt,
|
||||
Dictionary<string, object> Metadata
|
||||
);
|
||||
```
|
||||
|
||||
**TradeGrade Enum:**
|
||||
```csharp
|
||||
public enum TradeGrade
|
||||
{
|
||||
APlus = 6, // 0.90+ Exceptional setup
|
||||
A = 5, // 0.80+ Strong setup
|
||||
B = 4, // 0.70+ Good setup
|
||||
C = 3, // 0.60+ Acceptable setup
|
||||
D = 2, // 0.50+ Marginal setup
|
||||
F = 1 // <0.50 Reject trade
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task A2: Create FactorCalculators.cs
|
||||
**Location:** `src/NT8.Core/Intelligence/FactorCalculators.cs`
|
||||
|
||||
**Deliverables:**
|
||||
Base interface and individual factor calculators for:
|
||||
1. **ORB Setup Validity** (0.0 - 1.0)
|
||||
2. **Trend Alignment** (0.0 - 1.0)
|
||||
3. **Volatility Regime** (0.0 - 1.0)
|
||||
4. **Time-in-Session** (0.0 - 1.0)
|
||||
5. **Recent Execution Quality** (0.0 - 1.0)
|
||||
|
||||
**Interface:**
|
||||
```csharp
|
||||
public interface IFactorCalculator
|
||||
{
|
||||
FactorType Type { get; }
|
||||
ConfluenceFactor Calculate(StrategyIntent intent, StrategyContext context, MarketData data);
|
||||
}
|
||||
```
|
||||
|
||||
**Factor 1: ORB Setup Validity**
|
||||
```csharp
|
||||
Score Calculation:
|
||||
- ORB range > minimum threshold: +0.3
|
||||
- Clean breakout (no wicks): +0.2
|
||||
- Volume confirmation (>avg): +0.2
|
||||
- Time since ORB complete < 2 hrs: +0.3
|
||||
|
||||
Max Score: 1.0
|
||||
```
|
||||
|
||||
**Factor 2: Trend Alignment**
|
||||
```csharp
|
||||
Score Calculation:
|
||||
- Price above AVWAP (long): +0.4
|
||||
- AVWAP slope aligned: +0.3
|
||||
- Recent bars confirm trend: +0.3
|
||||
|
||||
Max Score: 1.0
|
||||
```
|
||||
|
||||
**Factor 3: Volatility Regime**
|
||||
```csharp
|
||||
Score Calculation:
|
||||
Normal volatility (0.8-1.2x avg): 1.0
|
||||
Low volatility (<0.8x): 0.7
|
||||
High volatility (>1.2x): 0.5
|
||||
Extreme volatility (>1.5x): 0.3
|
||||
```
|
||||
|
||||
**Factor 4: Time-in-Session**
|
||||
```csharp
|
||||
Score Calculation:
|
||||
First 2 hours (9:30-11:30): 1.0
|
||||
Mid-day (11:30-14:00): 0.6
|
||||
Last hour (15:00-16:00): 0.8
|
||||
After hours: 0.3
|
||||
```
|
||||
|
||||
**Factor 5: Recent Execution Quality**
|
||||
```csharp
|
||||
Score Calculation:
|
||||
Last 10 trades avg quality:
|
||||
- Excellent: 1.0
|
||||
- Good: 0.8
|
||||
- Fair: 0.6
|
||||
- Poor: 0.4
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task A3: Create ConfluenceScorer.cs
|
||||
**Location:** `src/NT8.Core/Intelligence/ConfluenceScorer.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Calculate overall confluence score
|
||||
- Aggregate factor scores with weights
|
||||
- Map raw score to trade grade
|
||||
- Thread-safe scoring
|
||||
- Detailed score breakdown
|
||||
|
||||
**Key Features:**
|
||||
- Configurable factor weights
|
||||
- Dynamic weight adjustment
|
||||
- Score history tracking
|
||||
- Performance analytics
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public ConfluenceScore CalculateScore(
|
||||
StrategyIntent intent,
|
||||
StrategyContext context,
|
||||
List<IFactorCalculator> factors);
|
||||
|
||||
public TradeGrade MapScoreToGrade(double weightedScore);
|
||||
public void UpdateFactorWeights(Dictionary<FactorType, double> weights);
|
||||
public ConfluenceStatistics GetHistoricalStats();
|
||||
```
|
||||
|
||||
**Scoring Algorithm:**
|
||||
```csharp
|
||||
WeightedScore = Sum(Factor.Score × Factor.Weight) / Sum(Weights)
|
||||
|
||||
Grade Mapping:
|
||||
0.90+ → A+ (Exceptional)
|
||||
0.80+ → A (Strong)
|
||||
0.70+ → B (Good)
|
||||
0.60+ → C (Acceptable)
|
||||
0.50+ → D (Marginal)
|
||||
<0.50 → F (Reject)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase B: Regime Detection (60 minutes)
|
||||
|
||||
### Task B1: Create RegimeModels.cs
|
||||
**Location:** `src/NT8.Core/Intelligence/RegimeModels.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- `VolatilityRegime` enum - Low/Normal/High/Extreme
|
||||
- `TrendRegime` enum - StrongUp/WeakUp/Range/WeakDown/StrongDown
|
||||
- `RegimeState` record - Current market regime
|
||||
- `RegimeTransition` record - Regime change event
|
||||
- `RegimeHistory` record - Historical regime tracking
|
||||
|
||||
**RegimeState:**
|
||||
```csharp
|
||||
public record RegimeState(
|
||||
string Symbol,
|
||||
VolatilityRegime VolatilityRegime,
|
||||
TrendRegime TrendRegime,
|
||||
double VolatilityScore, // Current volatility vs normal
|
||||
double TrendStrength, // -1.0 to +1.0
|
||||
DateTime LastUpdate,
|
||||
TimeSpan RegimeDuration, // How long in current regime
|
||||
Dictionary<string, object> Indicators
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task B2: Create VolatilityRegimeDetector.cs
|
||||
**Location:** `src/NT8.Core/Intelligence/VolatilityRegimeDetector.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Calculate current volatility vs historical
|
||||
- Classify into regime (Low/Normal/High/Extreme)
|
||||
- Detect regime transitions
|
||||
- Track regime duration
|
||||
- Alert on regime changes
|
||||
|
||||
**Volatility Calculation:**
|
||||
```csharp
|
||||
Current ATR vs 20-day Average ATR:
|
||||
< 0.6x → Low (expansion likely)
|
||||
0.6-0.8x → Below Normal
|
||||
0.8-1.2x → Normal
|
||||
1.2-1.5x → Elevated
|
||||
1.5-2.0x → High
|
||||
> 2.0x → Extreme (reduce size)
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public VolatilityRegime DetectRegime(string symbol, double currentATR, double normalATR);
|
||||
public bool IsRegimeTransition(VolatilityRegime current, VolatilityRegime previous);
|
||||
public double CalculateVolatilityScore(double currentATR, double normalATR);
|
||||
public void UpdateRegimeHistory(string symbol, VolatilityRegime regime);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task B3: Create TrendRegimeDetector.cs
|
||||
**Location:** `src/NT8.Core/Intelligence/TrendRegimeDetector.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Detect trend direction and strength
|
||||
- Identify ranging vs trending markets
|
||||
- Calculate trend persistence
|
||||
- Measure trend quality
|
||||
|
||||
**Trend Detection:**
|
||||
```csharp
|
||||
Using Price vs AVWAP + Slope:
|
||||
|
||||
Strong Uptrend:
|
||||
- Price > AVWAP
|
||||
- AVWAP slope > threshold
|
||||
- Higher highs, higher lows
|
||||
- Score: +0.8 to +1.0
|
||||
|
||||
Weak Uptrend:
|
||||
- Price > AVWAP
|
||||
- AVWAP slope positive but weak
|
||||
- Score: +0.3 to +0.7
|
||||
|
||||
Range:
|
||||
- Price oscillating around AVWAP
|
||||
- Low slope
|
||||
- Score: -0.2 to +0.2
|
||||
|
||||
Weak Downtrend:
|
||||
- Price < AVWAP
|
||||
- AVWAP slope negative but weak
|
||||
- Score: -0.7 to -0.3
|
||||
|
||||
Strong Downtrend:
|
||||
- Price < AVWAP
|
||||
- AVWAP slope < threshold
|
||||
- Lower highs, lower lows
|
||||
- Score: -1.0 to -0.8
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public TrendRegime DetectTrend(string symbol, List<BarData> bars, double avwap);
|
||||
public double CalculateTrendStrength(List<BarData> bars, double avwap);
|
||||
public bool IsRanging(List<BarData> bars, double threshold);
|
||||
public TrendQuality AssessTrendQuality(List<BarData> bars);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task B4: Create RegimeManager.cs
|
||||
**Location:** `src/NT8.Core/Intelligence/RegimeManager.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Coordinate volatility and trend detection
|
||||
- Maintain current regime state per symbol
|
||||
- Track regime transitions
|
||||
- Provide regime-based recommendations
|
||||
- Thread-safe regime tracking
|
||||
|
||||
**Key Features:**
|
||||
- Real-time regime updates
|
||||
- Regime change notifications
|
||||
- Historical regime tracking
|
||||
- Performance by regime
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public void UpdateRegime(string symbol, BarData bar, double avwap, double atr, double normalATR);
|
||||
public RegimeState GetCurrentRegime(string symbol);
|
||||
public bool ShouldAdjustStrategy(string symbol, StrategyIntent intent);
|
||||
public List<RegimeTransition> GetRecentTransitions(string symbol, TimeSpan period);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase C: Risk Mode Framework (60 minutes)
|
||||
|
||||
### Task C1: Create RiskModeModels.cs
|
||||
**Location:** `src/NT8.Core/Intelligence/RiskModeModels.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- `RiskMode` enum - ECP/PCP/DCP/HR
|
||||
- `RiskModeConfig` record - Mode-specific settings
|
||||
- `ModeTransitionRule` record - Transition conditions
|
||||
- `RiskModeState` record - Current mode state
|
||||
|
||||
**RiskMode Enum:**
|
||||
```csharp
|
||||
public enum RiskMode
|
||||
{
|
||||
HR = 0, // High Risk - minimal exposure
|
||||
DCP = 1, // Diminished Confidence Play
|
||||
PCP = 2, // Primary Confidence Play (default)
|
||||
ECP = 3 // Elevated Confidence Play
|
||||
}
|
||||
```
|
||||
|
||||
**RiskModeConfig:**
|
||||
```csharp
|
||||
public record RiskModeConfig(
|
||||
RiskMode Mode,
|
||||
double SizeMultiplier, // Position size adjustment
|
||||
TradeGrade MinimumGrade, // Minimum grade to trade
|
||||
double MaxDailyRisk, // Daily risk cap
|
||||
int MaxConcurrentTrades, // Max open positions
|
||||
bool AggressiveEntries, // Allow aggressive entries
|
||||
Dictionary<string, object> CustomSettings
|
||||
);
|
||||
|
||||
Example Configs:
|
||||
ECP: 1.5x size, B+ minimum, aggressive entries
|
||||
PCP: 1.0x size, B minimum, normal entries
|
||||
DCP: 0.5x size, A- minimum, conservative only
|
||||
HR: 0.0x size, reject all trades
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task C2: Create RiskModeManager.cs
|
||||
**Location:** `src/NT8.Core/Intelligence/RiskModeManager.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Manage current risk mode
|
||||
- Automatic mode transitions based on P&L
|
||||
- Manual mode override capability
|
||||
- Mode-specific trading rules
|
||||
- Thread-safe mode management
|
||||
|
||||
**Mode Transition Logic:**
|
||||
```csharp
|
||||
Start of Day: PCP (Primary Confidence Play)
|
||||
|
||||
Transition to ECP:
|
||||
- Daily P&L > +$500 (or 5R)
|
||||
- Last 5 trades: 80%+ win rate
|
||||
- No recent drawdowns
|
||||
|
||||
Transition to DCP:
|
||||
- Daily P&L < -$200 (or -2R)
|
||||
- Last 5 trades: <50% win rate
|
||||
- Recent execution quality declining
|
||||
|
||||
Transition to HR:
|
||||
- Daily loss limit approached (80%)
|
||||
- 3+ consecutive losses
|
||||
- Extreme volatility regime
|
||||
- Manual override
|
||||
|
||||
Recovery from DCP to PCP:
|
||||
- 2+ winning trades in a row
|
||||
- Execution quality improved
|
||||
- Volatility normalized
|
||||
|
||||
Recovery from HR to DCP:
|
||||
- Next trading day (automatic reset)
|
||||
- Manual override after review
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public void UpdateRiskMode(double dailyPnL, int winStreak, int lossStreak);
|
||||
public RiskMode GetCurrentMode();
|
||||
public RiskModeConfig GetModeConfig(RiskMode mode);
|
||||
public bool ShouldTransitionMode(RiskMode current, PerformanceMetrics metrics);
|
||||
public void OverrideMode(RiskMode mode, string reason);
|
||||
public void ResetToDefault();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task C3: Create GradeFilter.cs
|
||||
**Location:** `src/NT8.Core/Intelligence/GradeFilter.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Filter trades by grade based on risk mode
|
||||
- Grade-based position sizing multipliers
|
||||
- Risk mode gating logic
|
||||
- Trade rejection reasons
|
||||
|
||||
**Grade Filtering Rules:**
|
||||
```csharp
|
||||
ECP Mode (Elevated Confidence):
|
||||
- Accept: A+, A, B+, B
|
||||
- Size: A+ = 1.5x, A = 1.25x, B+ = 1.1x, B = 1.0x
|
||||
- Reject: C and below
|
||||
|
||||
PCP Mode (Primary Confidence):
|
||||
- Accept: A+, A, B+, B, C+
|
||||
- Size: A+ = 1.25x, A = 1.1x, B = 1.0x, C+ = 0.9x
|
||||
- Reject: C and below
|
||||
|
||||
DCP Mode (Diminished Confidence):
|
||||
- Accept: A+, A only
|
||||
- Size: A+ = 0.75x, A = 0.5x
|
||||
- Reject: B+ and below
|
||||
|
||||
HR Mode (High Risk):
|
||||
- Accept: None
|
||||
- Reject: All trades
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public bool ShouldAcceptTrade(TradeGrade grade, RiskMode mode);
|
||||
public double GetSizeMultiplier(TradeGrade grade, RiskMode mode);
|
||||
public string GetRejectionReason(TradeGrade grade, RiskMode mode);
|
||||
public TradeGrade GetMinimumGrade(RiskMode mode);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase D: Grade-Based Sizing Integration (45 minutes)
|
||||
|
||||
### Task D1: Create GradeBasedSizer.cs
|
||||
**Location:** `src/NT8.Core/Sizing/GradeBasedSizer.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Integrate confluence score with position sizing
|
||||
- Apply grade-based multipliers
|
||||
- Combine with risk mode adjustments
|
||||
- Override existing sizing with grade awareness
|
||||
|
||||
**Sizing Flow:**
|
||||
```csharp
|
||||
1. Base Size (from Phase 2 sizer):
|
||||
BaseContracts = FixedRisk OR OptimalF OR VolatilityAdjusted
|
||||
|
||||
2. Grade Multiplier (from confluence score):
|
||||
GradeMultiplier = GetSizeMultiplier(grade, riskMode)
|
||||
|
||||
3. Risk Mode Multiplier:
|
||||
ModeMultiplier = riskModeConfig.SizeMultiplier
|
||||
|
||||
4. Final Size:
|
||||
FinalContracts = BaseContracts × GradeMultiplier × ModeMultiplier
|
||||
FinalContracts = Clamp(FinalContracts, MinContracts, MaxContracts)
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public SizingResult CalculateGradeBasedSize(
|
||||
StrategyIntent intent,
|
||||
StrategyContext context,
|
||||
ConfluenceScore confluenceScore,
|
||||
RiskMode riskMode,
|
||||
SizingConfig baseConfig);
|
||||
|
||||
public double CombineMultipliers(double gradeMultiplier, double modeMultiplier);
|
||||
public int ApplyConstraints(int calculatedSize, int min, int max);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task D2: Update AdvancedPositionSizer.cs
|
||||
**Location:** `src/NT8.Core/Sizing/AdvancedPositionSizer.cs`
|
||||
|
||||
**Add method (don't modify existing):**
|
||||
```csharp
|
||||
public SizingResult CalculateSizeWithGrade(
|
||||
StrategyIntent intent,
|
||||
StrategyContext context,
|
||||
SizingConfig config,
|
||||
ConfluenceScore confluenceScore,
|
||||
RiskMode riskMode);
|
||||
```
|
||||
|
||||
**Implementation:**
|
||||
- Call existing CalculateSize() for base sizing
|
||||
- Apply grade-based multiplier
|
||||
- Apply risk mode multiplier
|
||||
- Return enhanced SizingResult with metadata
|
||||
|
||||
---
|
||||
|
||||
## Phase E: Strategy Enhancement (60 minutes)
|
||||
|
||||
### Task E1: Create AVWAPCalculator.cs
|
||||
**Location:** `src/NT8.Core/Indicators/AVWAPCalculator.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Anchored VWAP calculation
|
||||
- Anchor points (day start, week start, custom)
|
||||
- Rolling VWAP updates
|
||||
- Slope calculation
|
||||
|
||||
**AVWAP Formula:**
|
||||
```csharp
|
||||
VWAP = Sum(Price × Volume) / Sum(Volume)
|
||||
|
||||
Anchored: Reset accumulation at anchor point
|
||||
- Day: Reset at 9:30 AM each day
|
||||
- Week: Reset Monday 9:30 AM
|
||||
- Custom: User-specified time
|
||||
|
||||
Slope = (Current VWAP - VWAP 10 bars ago) / 10
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public double Calculate(List<BarData> bars, DateTime anchorTime);
|
||||
public void Update(double price, long volume);
|
||||
public double GetSlope(int lookback);
|
||||
public void ResetAnchor(DateTime newAnchor);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task E2: Create VolumeProfileAnalyzer.cs
|
||||
**Location:** `src/NT8.Core/Indicators/VolumeProfileAnalyzer.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Volume by price level (VPOC)
|
||||
- High volume nodes
|
||||
- Low volume nodes (gaps)
|
||||
- Value area calculation
|
||||
|
||||
**Volume Profile Concepts:**
|
||||
```csharp
|
||||
VPOC (Volume Point of Control):
|
||||
- Price level with highest volume
|
||||
- Acts as magnet for price
|
||||
|
||||
High Volume Nodes:
|
||||
- Volume > 1.5x average
|
||||
- Support/resistance levels
|
||||
|
||||
Low Volume Nodes:
|
||||
- Volume < 0.5x average
|
||||
- Price gaps quickly through
|
||||
|
||||
Value Area:
|
||||
- 70% of volume traded
|
||||
- Fair value range
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public double GetVPOC(List<BarData> bars);
|
||||
public List<double> GetHighVolumeNodes(List<BarData> bars);
|
||||
public List<double> GetLowVolumeNodes(List<BarData> bars);
|
||||
public ValueArea CalculateValueArea(List<BarData> bars);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task E3: Enhance SimpleORBStrategy
|
||||
**Location:** `src/NT8.Strategies/Examples/SimpleORBStrategy.cs`
|
||||
|
||||
**Add confluence awareness (don't break existing):**
|
||||
- Calculate AVWAP filter
|
||||
- Check volume profile
|
||||
- Use confluence scorer
|
||||
- Apply grade-based sizing
|
||||
|
||||
**Enhanced OnBar Logic:**
|
||||
```csharp
|
||||
public StrategyIntent? OnBar(BarData bar, StrategyContext context)
|
||||
{
|
||||
// Existing ORB logic...
|
||||
if (breakoutDetected)
|
||||
{
|
||||
// NEW: Add confluence factors
|
||||
var factors = new List<ConfluenceFactor>
|
||||
{
|
||||
CalculateORBValidity(),
|
||||
CalculateTrendAlignment(bar, avwap),
|
||||
CalculateVolatilityRegime(),
|
||||
CalculateTimingFactor(bar.Time),
|
||||
CalculateExecutionQuality()
|
||||
};
|
||||
|
||||
var confluenceScore = _scorer.CalculateScore(intent, context, factors);
|
||||
|
||||
// Check grade filter
|
||||
if (!_gradeFilter.ShouldAcceptTrade(confluenceScore.Grade, currentRiskMode))
|
||||
{
|
||||
_logger.LogInfo("Trade rejected: Grade {0}, Mode {1}",
|
||||
confluenceScore.Grade, currentRiskMode);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Add confluence metadata to intent
|
||||
intent.Metadata["confluence_score"] = confluenceScore;
|
||||
intent.Confidence = confluenceScore.WeightedScore;
|
||||
|
||||
return intent;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase F: Comprehensive Testing (75 minutes)
|
||||
|
||||
### Task F1: ConfluenceScorerTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Intelligence/ConfluenceScorerTests.cs`
|
||||
|
||||
**Test Coverage:**
|
||||
- Individual factor calculations
|
||||
- Score aggregation logic
|
||||
- Grade mapping accuracy
|
||||
- Weight application
|
||||
- Edge cases (all factors 0.0, all factors 1.0)
|
||||
- Thread safety
|
||||
|
||||
**Minimum:** 20 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F2: RegimeDetectionTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Intelligence/RegimeDetectionTests.cs`
|
||||
|
||||
**Test Coverage:**
|
||||
- Volatility regime classification
|
||||
- Trend regime detection
|
||||
- Regime transitions
|
||||
- Historical regime tracking
|
||||
- Regime duration calculation
|
||||
|
||||
**Minimum:** 18 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F3: RiskModeManagerTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Intelligence/RiskModeManagerTests.cs`
|
||||
|
||||
**Test Coverage:**
|
||||
- Mode transitions (PCP→ECP, PCP→DCP, DCP→HR)
|
||||
- Automatic mode updates
|
||||
- Manual overrides
|
||||
- Grade filtering by mode
|
||||
- Size multipliers by mode
|
||||
|
||||
**Minimum:** 15 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F4: GradeBasedSizerTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Sizing/GradeBasedSizerTests.cs`
|
||||
|
||||
**Test Coverage:**
|
||||
- Base size calculation
|
||||
- Grade multiplier application
|
||||
- Risk mode multiplier
|
||||
- Combined multipliers
|
||||
- Constraint application
|
||||
|
||||
**Minimum:** 12 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F5: AVWAPCalculatorTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Indicators/AVWAPCalculatorTests.cs`
|
||||
|
||||
**Test Coverage:**
|
||||
- AVWAP calculation accuracy
|
||||
- Anchor point handling
|
||||
- Slope calculation
|
||||
- Rolling updates
|
||||
|
||||
**Minimum:** 10 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F6: Phase4IntegrationTests.cs
|
||||
**Location:** `tests/NT8.Integration.Tests/Phase4IntegrationTests.cs`
|
||||
|
||||
**Test Coverage:**
|
||||
- Full flow: Intent → Confluence → Grade → Mode Filter → Sizing
|
||||
- Grade-based rejection scenarios
|
||||
- Risk mode transitions during trading
|
||||
- Enhanced strategy execution
|
||||
- Regime-aware trading
|
||||
|
||||
**Minimum:** 12 tests
|
||||
|
||||
---
|
||||
|
||||
## Phase G: Integration & Verification (45 minutes)
|
||||
|
||||
### Task G1: Performance Benchmarks
|
||||
**Location:** `tests/NT8.Performance.Tests/Phase4PerformanceTests.cs`
|
||||
|
||||
**Benchmarks:**
|
||||
- Confluence score calculation: <5ms
|
||||
- Regime detection: <3ms
|
||||
- Grade filtering: <1ms
|
||||
- Risk mode update: <2ms
|
||||
- Overall intelligence flow: <15ms
|
||||
|
||||
---
|
||||
|
||||
### Task G2: Build Verification
|
||||
**Command:** `.\verify-build.bat`
|
||||
|
||||
**Requirements:**
|
||||
- Zero errors
|
||||
- Zero warnings for new Phase 4 code
|
||||
- All tests passing (150+ total)
|
||||
- Coverage >80%
|
||||
|
||||
---
|
||||
|
||||
### Task G3: Documentation
|
||||
**Files to update:**
|
||||
- Create Phase4_Completion_Report.md
|
||||
- Update API_REFERENCE.md with intelligence interfaces
|
||||
- Add confluence scoring examples
|
||||
- Document risk modes
|
||||
|
||||
---
|
||||
|
||||
## Success Criteria
|
||||
|
||||
### Code Quality
|
||||
- ✅ C# 5.0 syntax only
|
||||
- ✅ Thread-safe (locks on shared state)
|
||||
- ✅ XML docs on all public members
|
||||
- ✅ Comprehensive logging
|
||||
- ✅ No breaking changes
|
||||
|
||||
### Testing
|
||||
- ✅ >150 total tests passing
|
||||
- ✅ >80% code coverage
|
||||
- ✅ All scoring scenarios tested
|
||||
- ✅ All regime scenarios tested
|
||||
- ✅ Integration tests pass
|
||||
|
||||
### Performance
|
||||
- ✅ Confluence scoring <5ms
|
||||
- ✅ Regime detection <3ms
|
||||
- ✅ Grade filtering <1ms
|
||||
- ✅ Overall flow <15ms
|
||||
|
||||
### Integration
|
||||
- ✅ Works with Phase 2-3
|
||||
- ✅ Grade-based sizing operational
|
||||
- ✅ Risk modes functional
|
||||
- ✅ Regime detection accurate
|
||||
|
||||
---
|
||||
|
||||
## File Creation Checklist
|
||||
|
||||
### New Files (18):
|
||||
**Intelligence (9):**
|
||||
- [ ] `src/NT8.Core/Intelligence/ConfluenceModels.cs`
|
||||
- [ ] `src/NT8.Core/Intelligence/FactorCalculators.cs`
|
||||
- [ ] `src/NT8.Core/Intelligence/ConfluenceScorer.cs`
|
||||
- [ ] `src/NT8.Core/Intelligence/RegimeModels.cs`
|
||||
- [ ] `src/NT8.Core/Intelligence/VolatilityRegimeDetector.cs`
|
||||
- [ ] `src/NT8.Core/Intelligence/TrendRegimeDetector.cs`
|
||||
- [ ] `src/NT8.Core/Intelligence/RegimeManager.cs`
|
||||
- [ ] `src/NT8.Core/Intelligence/RiskModeModels.cs`
|
||||
- [ ] `src/NT8.Core/Intelligence/RiskModeManager.cs`
|
||||
- [ ] `src/NT8.Core/Intelligence/GradeFilter.cs`
|
||||
|
||||
**Sizing (1):**
|
||||
- [ ] `src/NT8.Core/Sizing/GradeBasedSizer.cs`
|
||||
|
||||
**Indicators (2):**
|
||||
- [ ] `src/NT8.Core/Indicators/AVWAPCalculator.cs`
|
||||
- [ ] `src/NT8.Core/Indicators/VolumeProfileAnalyzer.cs`
|
||||
|
||||
**Tests (6):**
|
||||
- [ ] `tests/NT8.Core.Tests/Intelligence/ConfluenceScorerTests.cs`
|
||||
- [ ] `tests/NT8.Core.Tests/Intelligence/RegimeDetectionTests.cs`
|
||||
- [ ] `tests/NT8.Core.Tests/Intelligence/RiskModeManagerTests.cs`
|
||||
- [ ] `tests/NT8.Core.Tests/Sizing/GradeBasedSizerTests.cs`
|
||||
- [ ] `tests/NT8.Core.Tests/Indicators/AVWAPCalculatorTests.cs`
|
||||
- [ ] `tests/NT8.Integration.Tests/Phase4IntegrationTests.cs`
|
||||
|
||||
### Updated Files (2):
|
||||
- [ ] `src/NT8.Core/Sizing/AdvancedPositionSizer.cs` - ADD grade-based method
|
||||
- [ ] `src/NT8.Strategies/Examples/SimpleORBStrategy.cs` - ADD confluence awareness
|
||||
|
||||
**Total:** 18 new files, 2 updated files
|
||||
|
||||
---
|
||||
|
||||
## Estimated Timeline
|
||||
|
||||
| Phase | Tasks | Time | Cumulative |
|
||||
|-------|-------|------|------------|
|
||||
| **A** | Confluence Foundation | 60 min | 1:00 |
|
||||
| **B** | Regime Detection | 60 min | 2:00 |
|
||||
| **C** | Risk Mode Framework | 60 min | 3:00 |
|
||||
| **D** | Grade-Based Sizing | 45 min | 3:45 |
|
||||
| **E** | Strategy Enhancement | 60 min | 4:45 |
|
||||
| **F** | Testing | 75 min | 6:00 |
|
||||
| **G** | Verification | 45 min | 6:45 |
|
||||
|
||||
**Total:** 6-7 hours (budget 4-5 hours for Kilocode efficiency)
|
||||
|
||||
---
|
||||
|
||||
## Critical Notes
|
||||
|
||||
### Modifications to Existing Code
|
||||
**IMPORTANT:** Only these files can be modified:
|
||||
- ✅ `src/NT8.Core/Sizing/AdvancedPositionSizer.cs` - ADD method only
|
||||
- ✅ `src/NT8.Strategies/Examples/SimpleORBStrategy.cs` - ADD features only
|
||||
|
||||
**FORBIDDEN:**
|
||||
- ❌ Do NOT modify interfaces
|
||||
- ❌ Do NOT modify Phase 1-3 core implementations
|
||||
- ❌ Do NOT change existing method signatures
|
||||
|
||||
### Thread Safety
|
||||
All intelligence classes MUST use proper locking:
|
||||
```csharp
|
||||
private readonly object _lock = new object();
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
// Shared state access
|
||||
}
|
||||
```
|
||||
|
||||
### C# 5.0 Compliance
|
||||
Verify after each file - same restrictions as Phase 2-3.
|
||||
|
||||
---
|
||||
|
||||
## Ready to Start?
|
||||
|
||||
**Paste into Kilocode Code Mode:**
|
||||
|
||||
```
|
||||
I'm ready to implement Phase 4: Intelligence & Grading.
|
||||
|
||||
Follow Phase4_Implementation_Guide.md starting with Phase A, Task A1.
|
||||
|
||||
CRITICAL REQUIREMENTS:
|
||||
- C# 5.0 syntax ONLY
|
||||
- Thread-safe with locks on shared state
|
||||
- XML docs on all public members
|
||||
- NO interface modifications
|
||||
- NO breaking changes to Phase 1-3
|
||||
|
||||
File Creation Permissions:
|
||||
✅ CREATE in: src/NT8.Core/Intelligence/, src/NT8.Core/Indicators/
|
||||
✅ MODIFY (ADD ONLY): AdvancedPositionSizer.cs, SimpleORBStrategy.cs
|
||||
❌ FORBIDDEN: Any interface files, Phase 1-3 core implementations
|
||||
|
||||
Start with Task A1: Create ConfluenceModels.cs in src/NT8.Core/Intelligence/
|
||||
|
||||
After each file:
|
||||
1. Build (Ctrl+Shift+B)
|
||||
2. Verify zero errors
|
||||
3. Continue to next task
|
||||
|
||||
Let's begin with ConfluenceModels.cs!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Phase 4 will make your system INTELLIGENT!** 🧠
|
||||
740
docs/archive/phase-specs/Phase5_Implementation_Guide.md
Normal file
740
docs/archive/phase-specs/Phase5_Implementation_Guide.md
Normal file
@@ -0,0 +1,740 @@
|
||||
# Phase 5: Analytics & Reporting - Implementation Guide
|
||||
|
||||
**Estimated Time:** 3-4 hours
|
||||
**Complexity:** Medium
|
||||
**Dependencies:** Phase 4 Complete ✅
|
||||
|
||||
---
|
||||
|
||||
## Implementation Overview
|
||||
|
||||
Phase 5 adds comprehensive analytics and reporting capabilities. This is the "observe, measure, and optimize" layer that helps understand performance, identify what's working, and continuously improve the trading system.
|
||||
|
||||
**Core Concept:** What gets measured gets improved. Track everything, attribute performance, find patterns.
|
||||
|
||||
---
|
||||
|
||||
## Phase A: Trade Analytics Foundation (45 minutes)
|
||||
|
||||
### Task A1: Create AnalyticsModels.cs
|
||||
**Location:** `src/NT8.Core/Analytics/AnalyticsModels.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- `TradeRecord` record - Complete trade lifecycle
|
||||
- `TradeMetrics` record - Per-trade performance metrics
|
||||
- `PerformanceSnapshot` record - Point-in-time performance
|
||||
- `AttributionBreakdown` record - P&L attribution
|
||||
- `AnalyticsPeriod` enum - Daily/Weekly/Monthly/AllTime
|
||||
|
||||
**TradeRecord:**
|
||||
```csharp
|
||||
public record TradeRecord(
|
||||
string TradeId,
|
||||
string Symbol,
|
||||
string StrategyName,
|
||||
DateTime EntryTime,
|
||||
DateTime? ExitTime,
|
||||
OrderSide Side,
|
||||
int Quantity,
|
||||
double EntryPrice,
|
||||
double? ExitPrice,
|
||||
double RealizedPnL,
|
||||
double UnrealizedPnL,
|
||||
TradeGrade Grade,
|
||||
double ConfluenceScore,
|
||||
RiskMode RiskMode,
|
||||
VolatilityRegime VolatilityRegime,
|
||||
TrendRegime TrendRegime,
|
||||
int StopTicks,
|
||||
int TargetTicks,
|
||||
double RMultiple,
|
||||
TimeSpan Duration,
|
||||
Dictionary<string, object> Metadata
|
||||
);
|
||||
```
|
||||
|
||||
**TradeMetrics:**
|
||||
```csharp
|
||||
public record TradeMetrics(
|
||||
string TradeId,
|
||||
double PnL,
|
||||
double RMultiple,
|
||||
double MAE, // Maximum Adverse Excursion
|
||||
double MFE, // Maximum Favorable Excursion
|
||||
double Slippage,
|
||||
double Commission,
|
||||
double NetPnL,
|
||||
bool IsWinner,
|
||||
TimeSpan HoldTime,
|
||||
double ROI, // Return on Investment
|
||||
Dictionary<string, object> CustomMetrics
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task A2: Create TradeRecorder.cs
|
||||
**Location:** `src/NT8.Core/Analytics/TradeRecorder.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Record complete trade lifecycle
|
||||
- Track entry, exit, fills, modifications
|
||||
- Calculate trade metrics (MAE, MFE, R-multiple)
|
||||
- Thread-safe trade storage
|
||||
- Query interface for historical trades
|
||||
|
||||
**Key Features:**
|
||||
- Real-time trade tracking
|
||||
- Automatic metric calculation
|
||||
- Historical trade database (in-memory)
|
||||
- Export to CSV/JSON
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public void RecordEntry(string tradeId, StrategyIntent intent, OrderFill fill, ConfluenceScore score, RiskMode mode);
|
||||
public void RecordExit(string tradeId, OrderFill fill);
|
||||
public void RecordPartialFill(string tradeId, OrderFill fill);
|
||||
public TradeRecord GetTrade(string tradeId);
|
||||
public List<TradeRecord> GetTrades(DateTime start, DateTime end);
|
||||
public List<TradeRecord> GetTradesByGrade(TradeGrade grade);
|
||||
public List<TradeRecord> GetTradesByStrategy(string strategyName);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task A3: Create PerformanceCalculator.cs
|
||||
**Location:** `src/NT8.Core/Analytics/PerformanceCalculator.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Calculate performance metrics
|
||||
- Win rate, profit factor, expectancy
|
||||
- Sharpe ratio, Sortino ratio
|
||||
- Maximum drawdown, recovery factor
|
||||
- Risk-adjusted returns
|
||||
|
||||
**Performance Metrics:**
|
||||
```csharp
|
||||
Total Trades
|
||||
Win Rate = Wins / Total
|
||||
Loss Rate = Losses / Total
|
||||
Average Win = Sum(Winning Trades) / Wins
|
||||
Average Loss = Sum(Losing Trades) / Losses
|
||||
Profit Factor = Gross Profit / Gross Loss
|
||||
Expectancy = (Win% × AvgWin) - (Loss% × AvgLoss)
|
||||
|
||||
Sharpe Ratio = (Mean Return - Risk Free Rate) / Std Dev Returns
|
||||
Sortino Ratio = (Mean Return - Risk Free Rate) / Downside Dev
|
||||
Max Drawdown = Max(Peak - Trough) / Peak
|
||||
Recovery Factor = Net Profit / Max Drawdown
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public PerformanceMetrics Calculate(List<TradeRecord> trades);
|
||||
public double CalculateWinRate(List<TradeRecord> trades);
|
||||
public double CalculateProfitFactor(List<TradeRecord> trades);
|
||||
public double CalculateExpectancy(List<TradeRecord> trades);
|
||||
public double CalculateSharpeRatio(List<TradeRecord> trades, double riskFreeRate);
|
||||
public double CalculateMaxDrawdown(List<TradeRecord> trades);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase B: P&L Attribution (60 minutes)
|
||||
|
||||
### Task B1: Create AttributionModels.cs
|
||||
**Location:** `src/NT8.Core/Analytics/AttributionModels.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- `AttributionDimension` enum - Strategy/Grade/Regime/Time
|
||||
- `AttributionSlice` record - P&L by dimension
|
||||
- `AttributionReport` record - Complete attribution
|
||||
- `ContributionAnalysis` record - Factor contributions
|
||||
|
||||
**AttributionSlice:**
|
||||
```csharp
|
||||
public record AttributionSlice(
|
||||
string DimensionName,
|
||||
string DimensionValue,
|
||||
double TotalPnL,
|
||||
double AvgPnL,
|
||||
int TradeCount,
|
||||
double WinRate,
|
||||
double ProfitFactor,
|
||||
double Contribution // % of total P&L
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task B2: Create PnLAttributor.cs
|
||||
**Location:** `src/NT8.Core/Analytics/PnLAttributor.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Attribute P&L by strategy
|
||||
- Attribute P&L by trade grade
|
||||
- Attribute P&L by regime (volatility/trend)
|
||||
- Attribute P&L by time of day
|
||||
- Multi-dimensional attribution
|
||||
|
||||
**Attribution Examples:**
|
||||
|
||||
**By Grade:**
|
||||
```
|
||||
A+ Trades: $2,500 (50% of total, 10 trades, 80% win rate)
|
||||
A Trades: $1,200 (24% of total, 15 trades, 70% win rate)
|
||||
B Trades: $800 (16% of total, 20 trades, 60% win rate)
|
||||
C Trades: $500 (10% of total, 25 trades, 52% win rate)
|
||||
D Trades: -$1,000 (rejected most, 5 taken, 20% win rate)
|
||||
```
|
||||
|
||||
**By Regime:**
|
||||
```
|
||||
Low Vol Trending: $3,000 (60%)
|
||||
Normal Vol Trend: $1,500 (30%)
|
||||
High Vol Range: -$500 (-10%)
|
||||
Extreme Vol: $0 (no trades taken)
|
||||
```
|
||||
|
||||
**By Time:**
|
||||
```
|
||||
First Hour (9:30-10:30): $2,000 (40%)
|
||||
Mid-Day (10:30-14:00): $500 (10%)
|
||||
Last Hour (15:00-16:00): $2,500 (50%)
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public AttributionReport AttributeByGrade(List<TradeRecord> trades);
|
||||
public AttributionReport AttributeByRegime(List<TradeRecord> trades);
|
||||
public AttributionReport AttributeByStrategy(List<TradeRecord> trades);
|
||||
public AttributionReport AttributeByTimeOfDay(List<TradeRecord> trades);
|
||||
public AttributionReport AttributeMultiDimensional(List<TradeRecord> trades, List<AttributionDimension> dimensions);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task B3: Create DrawdownAnalyzer.cs
|
||||
**Location:** `src/NT8.Core/Analytics/DrawdownAnalyzer.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Track equity curve
|
||||
- Identify drawdown periods
|
||||
- Calculate drawdown metrics
|
||||
- Attribute drawdowns to causes
|
||||
- Recovery time analysis
|
||||
|
||||
**Drawdown Metrics:**
|
||||
```csharp
|
||||
Max Drawdown Amount
|
||||
Max Drawdown %
|
||||
Current Drawdown
|
||||
Average Drawdown
|
||||
Number of Drawdowns
|
||||
Longest Drawdown Duration
|
||||
Average Recovery Time
|
||||
Drawdown Frequency
|
||||
Underwater Periods
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public DrawdownReport Analyze(List<TradeRecord> trades);
|
||||
public List<DrawdownPeriod> IdentifyDrawdowns(List<TradeRecord> trades);
|
||||
public DrawdownAttribution AttributeDrawdown(DrawdownPeriod period);
|
||||
public double CalculateRecoveryTime(DrawdownPeriod period);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase C: Grade & Regime Analysis (60 minutes)
|
||||
|
||||
### Task C1: Create GradePerformanceAnalyzer.cs
|
||||
**Location:** `src/NT8.Core/Analytics/GradePerformanceAnalyzer.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Performance metrics by grade
|
||||
- Grade accuracy analysis
|
||||
- Optimal grade thresholds
|
||||
- Grade distribution analysis
|
||||
|
||||
**Grade Performance Report:**
|
||||
```csharp
|
||||
A+ Trades:
|
||||
Count: 25
|
||||
Win Rate: 84%
|
||||
Avg P&L: $250
|
||||
Profit Factor: 4.2
|
||||
Expectancy: $210
|
||||
Total P&L: $5,250
|
||||
% of Total: 52%
|
||||
|
||||
Grade Accuracy:
|
||||
A+ predictions: 84% actually profitable
|
||||
A predictions: 72% actually profitable
|
||||
B predictions: 61% actually profitable
|
||||
C predictions: 48% actually profitable
|
||||
|
||||
Optimal Threshold:
|
||||
Current: Accept B+ and above
|
||||
Suggested: Accept A- and above (based on expectancy)
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public GradePerformanceReport AnalyzeByGrade(List<TradeRecord> trades);
|
||||
public double CalculateGradeAccuracy(TradeGrade grade, List<TradeRecord> trades);
|
||||
public TradeGrade FindOptimalThreshold(List<TradeRecord> trades);
|
||||
public Dictionary<TradeGrade, PerformanceMetrics> GetMetricsByGrade(List<TradeRecord> trades);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task C2: Create RegimePerformanceAnalyzer.cs
|
||||
**Location:** `src/NT8.Core/Analytics/RegimePerformanceAnalyzer.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Performance by volatility regime
|
||||
- Performance by trend regime
|
||||
- Combined regime analysis
|
||||
- Regime transition impact
|
||||
|
||||
**Regime Performance:**
|
||||
```csharp
|
||||
Low Volatility:
|
||||
Uptrend: $3,000 (15 trades, 73% win rate)
|
||||
Range: $500 (8 trades, 50% win rate)
|
||||
Downtrend: -$200 (5 trades, 40% win rate)
|
||||
|
||||
Normal Volatility:
|
||||
Uptrend: $2,500 (20 trades, 65% win rate)
|
||||
Range: $0 (12 trades, 50% win rate)
|
||||
Downtrend: -$500 (7 trades, 29% win rate)
|
||||
|
||||
High Volatility:
|
||||
All: -$300 (avoid trading in high vol)
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public RegimePerformanceReport AnalyzeByRegime(List<TradeRecord> trades);
|
||||
public PerformanceMetrics GetPerformance(VolatilityRegime volRegime, TrendRegime trendRegime, List<TradeRecord> trades);
|
||||
public List<RegimeTransitionImpact> AnalyzeTransitions(List<TradeRecord> trades);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task C3: Create ConfluenceValidator.cs
|
||||
**Location:** `src/NT8.Core/Analytics/ConfluenceValidator.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Validate confluence score accuracy
|
||||
- Factor importance analysis
|
||||
- Factor correlation to outcomes
|
||||
- Recommended factor weights
|
||||
|
||||
**Confluence Validation:**
|
||||
```csharp
|
||||
Factor Performance Analysis:
|
||||
|
||||
ORB Validity Factor:
|
||||
High (>0.8): 75% win rate, $180 avg
|
||||
Medium (0.5-0.8): 58% win rate, $80 avg
|
||||
Low (<0.5): 42% win rate, -$30 avg
|
||||
Importance: HIGH (0.35 weight recommended)
|
||||
|
||||
Trend Alignment:
|
||||
High: 68% win rate, $150 avg
|
||||
Medium: 55% win rate, $60 avg
|
||||
Low: 48% win rate, $20 avg
|
||||
Importance: MEDIUM (0.25 weight recommended)
|
||||
|
||||
Current Weights vs Recommended:
|
||||
ORB Validity: 0.25 → 0.35 (increase)
|
||||
Trend: 0.20 → 0.25 (increase)
|
||||
Volatility: 0.20 → 0.15 (decrease)
|
||||
Timing: 0.20 → 0.15 (decrease)
|
||||
Quality: 0.15 → 0.10 (decrease)
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public FactorAnalysisReport AnalyzeFactor(FactorType factor, List<TradeRecord> trades);
|
||||
public Dictionary<FactorType, double> CalculateFactorImportance(List<TradeRecord> trades);
|
||||
public Dictionary<FactorType, double> RecommendWeights(List<TradeRecord> trades);
|
||||
public bool ValidateScore(ConfluenceScore score, TradeOutcome outcome);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase D: Reporting & Visualization (45 minutes)
|
||||
|
||||
### Task D1: Create ReportModels.cs
|
||||
**Location:** `src/NT8.Core/Analytics/ReportModels.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- `DailyReport` record - Daily performance summary
|
||||
- `WeeklyReport` record - Weekly performance
|
||||
- `MonthlyReport` record - Monthly performance
|
||||
- `TradeBlotter` record - Trade log format
|
||||
- `EquityCurve` record - Equity progression
|
||||
|
||||
---
|
||||
|
||||
### Task D2: Create ReportGenerator.cs
|
||||
**Location:** `src/NT8.Core/Analytics/ReportGenerator.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Generate daily/weekly/monthly reports
|
||||
- Trade blotter with filtering
|
||||
- Equity curve data
|
||||
- Performance summary
|
||||
- Export to multiple formats (text, CSV, JSON)
|
||||
|
||||
**Report Example:**
|
||||
```
|
||||
=== Daily Performance Report ===
|
||||
Date: 2026-02-16
|
||||
|
||||
Summary:
|
||||
Total Trades: 8
|
||||
Winning Trades: 6 (75%)
|
||||
Losing Trades: 2 (25%)
|
||||
Total P&L: $1,250
|
||||
Average P&L: $156
|
||||
Largest Win: $450
|
||||
Largest Loss: -$120
|
||||
|
||||
Grade Distribution:
|
||||
A+: 2 trades, $900 P&L
|
||||
A: 3 trades, $550 P&L
|
||||
B: 2 trades, $100 P&L
|
||||
C: 1 trade, -$300 P&L (rejected most C grades)
|
||||
|
||||
Risk Mode:
|
||||
Started: PCP
|
||||
Ended: ECP (elevated after +$1,250)
|
||||
Transitions: 1 (PCP→ECP at +$500)
|
||||
|
||||
Top Contributing Factor:
|
||||
ORB Validity (avg 0.87 for winners)
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public DailyReport GenerateDailyReport(DateTime date, List<TradeRecord> trades);
|
||||
public WeeklyReport GenerateWeeklyReport(DateTime weekStart, List<TradeRecord> trades);
|
||||
public string ExportToText(Report report);
|
||||
public string ExportToCsv(List<TradeRecord> trades);
|
||||
public string ExportToJson(Report report);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task D3: Create TradeBlotter.cs
|
||||
**Location:** `src/NT8.Core/Analytics/TradeBlotter.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Filterable trade log
|
||||
- Sort by any column
|
||||
- Search functionality
|
||||
- Export capability
|
||||
- Real-time updates
|
||||
|
||||
**Blotter Columns:**
|
||||
```
|
||||
| Time | Symbol | Side | Qty | Entry | Exit | P&L | R-Mult | Grade | Regime | Duration |
|
||||
|--------|--------|------|-----|-------|-------|--------|--------|-------|--------|----------|
|
||||
| 10:05 | ES | Long | 3 | 4205 | 4221 | +$600 | 2.0R | A+ | LowVol | 45m |
|
||||
| 10:35 | ES | Long | 2 | 4210 | 4218 | +$200 | 1.0R | A | Normal | 28m |
|
||||
| 11:20 | ES | Short| 2 | 4215 | 4209 | +$150 | 0.75R | B+ | Normal | 15m |
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public List<TradeRecord> FilterByDate(DateTime start, DateTime end);
|
||||
public List<TradeRecord> FilterBySymbol(string symbol);
|
||||
public List<TradeRecord> FilterByGrade(TradeGrade grade);
|
||||
public List<TradeRecord> FilterByPnL(double minPnL, double maxPnL);
|
||||
public List<TradeRecord> SortBy(string column, SortDirection direction);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase E: Optimization Tools (60 minutes)
|
||||
|
||||
### Task E1: Create ParameterOptimizer.cs
|
||||
**Location:** `src/NT8.Core/Analytics/ParameterOptimizer.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Parameter sensitivity analysis
|
||||
- Walk-forward optimization
|
||||
- Grid search optimization
|
||||
- Optimal parameter discovery
|
||||
|
||||
**Optimization Example:**
|
||||
```csharp
|
||||
Parameter: ORB Minutes (15, 30, 45, 60)
|
||||
|
||||
Results:
|
||||
15 min: $2,500 (but high variance)
|
||||
30 min: $5,200 (current - OPTIMAL)
|
||||
45 min: $3,800
|
||||
60 min: $1,200 (too conservative)
|
||||
|
||||
Recommendation: Keep at 30 minutes
|
||||
|
||||
Parameter: Stop Ticks (6, 8, 10, 12)
|
||||
|
||||
Results:
|
||||
6 ticks: $3,000 (61% win rate, tight stops)
|
||||
8 ticks: $5,200 (current - OPTIMAL, 68% win rate)
|
||||
10 ticks: $4,800 (65% win rate, too wide)
|
||||
12 ticks: $4,000 (63% win rate, too wide)
|
||||
|
||||
Recommendation: Keep at 8 ticks
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public OptimizationResult OptimizeParameter(string paramName, List<double> values, List<TradeRecord> trades);
|
||||
public GridSearchResult GridSearch(Dictionary<string, List<double>> parameters, List<TradeRecord> trades);
|
||||
public WalkForwardResult WalkForwardTest(StrategyConfig config, List<BarData> historicalData);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task E2: Create MonteCarloSimulator.cs
|
||||
**Location:** `src/NT8.Core/Analytics/MonteCarloSimulator.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Monte Carlo scenario generation
|
||||
- Risk of ruin calculation
|
||||
- Confidence intervals
|
||||
- Worst-case scenario analysis
|
||||
|
||||
**Monte Carlo Analysis:**
|
||||
```csharp
|
||||
Based on 10,000 simulations of 100 trades:
|
||||
|
||||
Expected Return: $12,500
|
||||
95% Confidence Interval: $8,000 - $18,000
|
||||
Worst Case (5th percentile): $3,500
|
||||
Best Case (95th percentile): $22,000
|
||||
|
||||
Risk of Ruin (25% drawdown): 2.3%
|
||||
Risk of Ruin (50% drawdown): 0.1%
|
||||
|
||||
Max Drawdown Distribution:
|
||||
10th percentile: 8%
|
||||
25th percentile: 12%
|
||||
50th percentile (median): 18%
|
||||
75th percentile: 25%
|
||||
90th percentile: 32%
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public MonteCarloResult Simulate(List<TradeRecord> historicalTrades, int numSimulations, int numTrades);
|
||||
public double CalculateRiskOfRuin(List<TradeRecord> trades, double drawdownThreshold);
|
||||
public ConfidenceInterval CalculateConfidenceInterval(MonteCarloResult result, double confidenceLevel);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task E3: Create PortfolioOptimizer.cs
|
||||
**Location:** `src/NT8.Core/Analytics/PortfolioOptimizer.cs`
|
||||
|
||||
**Deliverables:**
|
||||
- Optimal strategy allocation
|
||||
- Correlation-based diversification
|
||||
- Risk-parity allocation
|
||||
- Sharpe-optimal portfolio
|
||||
|
||||
**Portfolio Optimization:**
|
||||
```csharp
|
||||
Current Allocation:
|
||||
ORB Strategy: 100%
|
||||
|
||||
Optimal Allocation (if you had multiple strategies):
|
||||
ORB Strategy: 60%
|
||||
VWAP Bounce: 25%
|
||||
Mean Reversion: 15%
|
||||
|
||||
Expected Results:
|
||||
Current Sharpe: 1.8
|
||||
Optimized Sharpe: 2.3
|
||||
Correlation Benefit: 0.5 Sharpe increase
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
```csharp
|
||||
public AllocationResult OptimizeAllocation(List<StrategyPerformance> strategies);
|
||||
public double CalculatePortfolioSharpe(Dictionary<string, double> allocation, List<StrategyPerformance> strategies);
|
||||
public Dictionary<string, double> RiskParityAllocation(List<StrategyPerformance> strategies);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase F: Comprehensive Testing (60 minutes)
|
||||
|
||||
### Task F1: TradeRecorderTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Analytics/TradeRecorderTests.cs`
|
||||
|
||||
**Minimum:** 15 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F2: PerformanceCalculatorTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Analytics/PerformanceCalculatorTests.cs`
|
||||
|
||||
**Minimum:** 20 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F3: PnLAttributorTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Analytics/PnLAttributorTests.cs`
|
||||
|
||||
**Minimum:** 18 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F4: GradePerformanceAnalyzerTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Analytics/GradePerformanceAnalyzerTests.cs`
|
||||
|
||||
**Minimum:** 15 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F5: OptimizationTests.cs
|
||||
**Location:** `tests/NT8.Core.Tests/Analytics/OptimizationTests.cs`
|
||||
|
||||
**Minimum:** 12 tests
|
||||
|
||||
---
|
||||
|
||||
### Task F6: Phase5IntegrationTests.cs
|
||||
**Location:** `tests/NT8.Integration.Tests/Phase5IntegrationTests.cs`
|
||||
|
||||
**Minimum:** 10 tests
|
||||
|
||||
---
|
||||
|
||||
## Phase G: Verification (30 minutes)
|
||||
|
||||
### Task G1: Build Verification
|
||||
**Command:** `.\verify-build.bat`
|
||||
|
||||
---
|
||||
|
||||
### Task G2: Documentation
|
||||
- Create Phase5_Completion_Report.md
|
||||
- Update API_REFERENCE.md
|
||||
- Add analytics examples
|
||||
|
||||
---
|
||||
|
||||
## Success Criteria
|
||||
|
||||
### Code Quality
|
||||
- ✅ C# 5.0 syntax only
|
||||
- ✅ Thread-safe
|
||||
- ✅ XML docs
|
||||
- ✅ No breaking changes
|
||||
|
||||
### Testing
|
||||
- ✅ >180 total tests passing
|
||||
- ✅ >80% coverage
|
||||
- ✅ All analytics scenarios tested
|
||||
|
||||
### Functionality
|
||||
- ✅ Trade recording works
|
||||
- ✅ Performance metrics accurate
|
||||
- ✅ Attribution functional
|
||||
- ✅ Reports generate correctly
|
||||
- ✅ Optimization tools operational
|
||||
|
||||
---
|
||||
|
||||
## File Creation Checklist
|
||||
|
||||
### New Files (17):
|
||||
**Analytics (13):**
|
||||
- [ ] `src/NT8.Core/Analytics/AnalyticsModels.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/TradeRecorder.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/PerformanceCalculator.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/AttributionModels.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/PnLAttributor.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/DrawdownAnalyzer.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/GradePerformanceAnalyzer.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/RegimePerformanceAnalyzer.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/ConfluenceValidator.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/ReportModels.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/ReportGenerator.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/TradeBlotter.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/ParameterOptimizer.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/MonteCarloSimulator.cs`
|
||||
- [ ] `src/NT8.Core/Analytics/PortfolioOptimizer.cs`
|
||||
|
||||
**Tests (6):**
|
||||
- [ ] `tests/NT8.Core.Tests/Analytics/TradeRecorderTests.cs`
|
||||
- [ ] `tests/NT8.Core.Tests/Analytics/PerformanceCalculatorTests.cs`
|
||||
- [ ] `tests/NT8.Core.Tests/Analytics/PnLAttributorTests.cs`
|
||||
- [ ] `tests/NT8.Core.Tests/Analytics/GradePerformanceAnalyzerTests.cs`
|
||||
- [ ] `tests/NT8.Core.Tests/Analytics/OptimizationTests.cs`
|
||||
- [ ] `tests/NT8.Integration.Tests/Phase5IntegrationTests.cs`
|
||||
|
||||
**Total:** 19 new files
|
||||
|
||||
---
|
||||
|
||||
## Estimated Timeline
|
||||
|
||||
| Phase | Tasks | Time | Cumulative |
|
||||
|-------|-------|------|------------|
|
||||
| **A** | Trade Analytics | 45 min | 0:45 |
|
||||
| **B** | P&L Attribution | 60 min | 1:45 |
|
||||
| **C** | Grade/Regime Analysis | 60 min | 2:45 |
|
||||
| **D** | Reporting | 45 min | 3:30 |
|
||||
| **E** | Optimization | 60 min | 4:30 |
|
||||
| **F** | Testing | 60 min | 5:30 |
|
||||
| **G** | Verification | 30 min | 6:00 |
|
||||
|
||||
**Total:** 6 hours (budget 3-4 hours for Kilocode efficiency)
|
||||
|
||||
---
|
||||
|
||||
## Ready to Start?
|
||||
|
||||
**Paste into Kilocode Code Mode:**
|
||||
|
||||
```
|
||||
I'm ready to implement Phase 5: Analytics & Reporting.
|
||||
|
||||
Follow Phase5_Implementation_Guide.md starting with Phase A, Task A1.
|
||||
|
||||
CRITICAL REQUIREMENTS:
|
||||
- C# 5.0 syntax ONLY
|
||||
- Thread-safe with locks on shared state
|
||||
- XML docs on all public members
|
||||
- NO interface modifications
|
||||
- NO breaking changes to Phase 1-4
|
||||
|
||||
File Creation Permissions:
|
||||
✅ CREATE in: src/NT8.Core/Analytics/
|
||||
✅ CREATE in: tests/NT8.Core.Tests/Analytics/
|
||||
❌ FORBIDDEN: Any interface files, Phase 1-4 core implementations
|
||||
|
||||
Start with Task A1: Create AnalyticsModels.cs in src/NT8.Core/Analytics/
|
||||
|
||||
After each file:
|
||||
1. Build (Ctrl+Shift+B)
|
||||
2. Verify zero errors
|
||||
3. Continue to next task
|
||||
|
||||
Let's begin with AnalyticsModels.cs!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Phase 5 will complete your analytics layer!** 📊
|
||||
Reference in New Issue
Block a user