chore: Add project configuration and documentation
Some checks failed
Build and Test / build (push) Has been cancelled

- Kilocode AI agent rules and guidelines
- Setup and implementation guides
- Architecture documentation
- Build and verification references
This commit is contained in:
2026-02-15 14:59:36 -05:00
parent 42efd83e5d
commit fb4f5d3bde
11 changed files with 2303 additions and 0 deletions

View File

@@ -0,0 +1,272 @@
# Mandatory Coding Patterns
These patterns MUST be followed in all code you write for the NT8 SDK.
## Thread Safety - Dictionary Access
ALL access to shared dictionaries MUST use locks.
### ❌ WRONG - No Lock
```csharp
_activeOrders[orderId] = orderStatus; // DANGEROUS!
```
### ✅ CORRECT - With Lock
```csharp
lock (_lock)
{
_activeOrders[orderId] = orderStatus;
}
```
### Rule
Every class with shared state MUST have:
```csharp
private readonly object _lock = new object();
```
Every access to shared collections MUST be inside:
```csharp
lock (_lock)
{
// Dictionary/List operations here
}
```
## Error Handling - Try-Catch Required
ALL public methods MUST have try-catch blocks.
### ❌ WRONG - No Error Handling
```csharp
public async Task<string> SubmitOrder(OrderRequest request)
{
var orderId = GenerateOrderId();
await _nt8Adapter.SubmitToNT8(orderStatus);
return orderId;
}
```
### ✅ CORRECT - With Error Handling
```csharp
public async Task<string> SubmitOrder(OrderRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
try
{
request.Validate();
}
catch (ArgumentException ex)
{
_logger.LogError("Order validation failed: {0}", ex.Message);
throw;
}
try
{
var orderId = GenerateOrderId();
await _nt8Adapter.SubmitToNT8(orderStatus);
return orderId;
}
catch (Exception ex)
{
_logger.LogError("Order submission failed: {0}", ex.Message);
throw;
}
}
```
### Pattern Template
```csharp
public ReturnType MethodName(Type parameter)
{
// 1. Validate parameters (throw ArgumentNullException/ArgumentException)
if (parameter == null)
throw new ArgumentNullException("parameter");
// 2. Try-catch for operation-specific errors
try
{
// Main logic
}
catch (SpecificException ex)
{
_logger.LogError("Specific error: {0}", ex.Message);
// Handle or re-throw
throw;
}
catch (Exception ex)
{
_logger.LogError("Unexpected error: {0}", ex.Message);
throw;
}
}
```
## Logging - Structured and Consistent
Use structured logging with string.Format (NOT string interpolation).
### Log Levels
#### LogTrace - Detailed Flow
```csharp
_logger.LogTrace("Entering method {0} with parameter {1}", methodName, param);
```
#### LogDebug - Normal Operations
```csharp
_logger.LogDebug("Order {0} state is {1}", orderId, state);
```
#### LogInformation - Important Events
```csharp
_logger.LogInformation("Order {0} submitted successfully at {1}", orderId, timestamp);
_logger.LogInformation("Order {0} filled: {1} contracts @ {2:F2}", orderId, qty, price);
```
#### LogWarning - Recoverable Issues
```csharp
_logger.LogWarning("Order validation failed: {0}", validationError);
_logger.LogWarning("Maximum active orders reached: {0}", maxOrders);
```
#### LogError - Failures
```csharp
_logger.LogError("Failed to submit order {0} to NT8: {1}", orderId, ex.Message);
_logger.LogError("Invalid state transition: {0} -> {1}", fromState, toState);
```
#### LogCritical - System Integrity Issues
```csharp
_logger.LogCritical("Emergency flatten failed for {0}: {1}", symbol, ex.Message);
```
### ❌ WRONG - String Interpolation
```csharp
_logger.LogInformation($"Order {orderId} submitted"); // C# 6+ feature!
```
### ✅ CORRECT - string.Format
```csharp
_logger.LogInformation("Order {0} submitted", orderId);
```
## XML Documentation - Required
ALL public and protected members MUST have XML documentation.
### ❌ WRONG - No Documentation
```csharp
public interface IOrderManager
{
Task<string> SubmitOrder(OrderRequest request);
}
```
### ✅ CORRECT - With Documentation
```csharp
/// <summary>
/// Order management interface - manages complete order lifecycle
/// </summary>
public interface IOrderManager
{
/// <summary>
/// Submit new order for execution
/// </summary>
/// <param name="request">Order request with all parameters</param>
/// <returns>Unique order ID for tracking</returns>
/// <exception cref="ArgumentNullException">Request is null</exception>
/// <exception cref="ArgumentException">Request validation fails</exception>
Task<string> SubmitOrder(OrderRequest request);
}
```
### Template
```csharp
/// <summary>
/// Brief description of what this does (one line)
/// </summary>
/// <param name="paramName">What this parameter represents</param>
/// <returns>What this method returns</returns>
/// <exception cref="ExceptionType">When this exception is thrown</exception>
public ReturnType MethodName(Type paramName)
{
// Implementation
}
```
## Constructor Pattern
### ❌ WRONG - No Validation
```csharp
public BasicOrderManager(ILogger logger, INT8OrderAdapter adapter)
{
_logger = logger;
_adapter = adapter;
}
```
### ✅ CORRECT - Validate Dependencies
```csharp
public BasicOrderManager(ILogger<BasicOrderManager> logger, INT8OrderAdapter adapter)
{
if (logger == null)
throw new ArgumentNullException("logger");
if (adapter == null)
throw new ArgumentNullException("adapter");
_logger = logger;
_adapter = adapter;
_activeOrders = new Dictionary<string, OrderStatus>();
_completedOrders = new Dictionary<string, OrderStatus>();
// Register callbacks
_adapter.RegisterOrderCallback(OnNT8OrderUpdate);
_logger.LogInformation("BasicOrderManager initialized");
}
```
## Event Raising Pattern
NEVER raise events inside locks (prevents deadlocks).
### ❌ WRONG - Event Inside Lock
```csharp
lock (_lock)
{
order.State = newState;
OrderStateChanged?.Invoke(this, eventArgs); // DEADLOCK RISK!
}
```
### ✅ CORRECT - Event Outside Lock
```csharp
OrderState previousState;
OrderState newState;
lock (_lock)
{
previousState = order.State;
order.State = newState;
// Update state inside lock
}
// Raise event OUTSIDE lock
RaiseOrderStateChanged(orderId, previousState, newState, reason);
```
## Verification Checklist
Before completing ANY method, verify:
- [ ] Parameter validation (ArgumentNullException/ArgumentException)
- [ ] Try-catch on operation
- [ ] Logging at appropriate level
- [ ] Lock around shared state access
- [ ] Events raised outside locks
- [ ] XML documentation on public members
- [ ] C# 5.0 syntax only (no $, ?., =>, etc.)

View File

@@ -0,0 +1,88 @@
# C# 5.0 Syntax Requirements
You are working on a .NET Framework 4.8 project that MUST use C# 5.0 syntax only.
## Forbidden C# 6+ Features
### String Interpolation (C# 6)
❌ NEVER use: `$"Order {orderId} at {price}"`
✅ ALWAYS use: `string.Format("Order {0} at {1}", orderId, price)`
### Null-Conditional Operators (C# 6)
❌ NEVER use: `var name = order?.Name`
❌ NEVER use: `var value = dict?[key]`
✅ ALWAYS use explicit null checks:
```csharp
var name = order != null ? order.Name : null;
if (dict != null && dict.ContainsKey(key)) { }
```
### Null-Coalescing Assignment (C# 8)
❌ NEVER use: `value ??= defaultValue;`
✅ ALWAYS use: `if (value == null) value = defaultValue;`
### Expression-Bodied Members (C# 6)
❌ NEVER use: `public int Property => value;`
❌ NEVER use: `public void Method() => DoSomething();`
✅ ALWAYS use full syntax:
```csharp
public int Property
{
get { return value; }
}
public void Method()
{
DoSomething();
}
```
### nameof Operator (C# 6)
❌ NEVER use: `throw new ArgumentNullException(nameof(param));`
✅ ALWAYS use: `throw new ArgumentNullException("param");`
### Auto-Property Initializers (C# 6)
❌ NEVER use: `public int Property { get; set; } = 10;`
✅ ALWAYS use constructor initialization:
```csharp
public int Property { get; set; }
public ClassName()
{
Property = 10;
}
```
### Using Static (C# 6)
❌ NEVER use: `using static System.Math;`
✅ ALWAYS use: `System.Math.Floor(...)`
### Tuple Syntax (C# 7)
❌ NEVER use: `var tuple = (name: "test", value: 1);`
✅ ALWAYS use: `Tuple<string, int>` or custom classes
### Pattern Matching (C# 7+)
❌ NEVER use: `if (obj is string str)`
✅ ALWAYS use: `if (obj is string) { var str = (string)obj; }`
### Local Functions (C# 7)
❌ NEVER use functions inside methods
✅ ALWAYS use private methods
### Out Variables (C# 7)
❌ NEVER use: `if (dict.TryGetValue(key, out var value))`
✅ ALWAYS use:
```csharp
OrderStatus value;
if (dict.TryGetValue(key, out value))
{
// Use value
}
```
## Verification
After writing ANY code, verify C# 5.0 compliance:
- No `$` signs except in string literals
- No `?.` or `?[` operators
- No `=>` except in lambda expressions
- No inline variable declarations in out parameters

View File

@@ -0,0 +1,63 @@
# File Modification Boundaries
You are implementing the OMS (Order Management System) for the NT8 SDK project.
## Allowed Modifications
You MAY create and modify files in these directories ONLY:
### Core OMS Implementation
- `src/NT8.Core/OMS/*.cs` - All OMS implementation files
- `src/NT8.Core/OMS/**/*.cs` - Any subdirectories under OMS
### Testing
- `tests/NT8.Core.Tests/OMS/*.cs` - OMS unit tests
- `tests/NT8.Core.Tests/OMS/**/*.cs` - OMS test subdirectories
- `tests/NT8.Core.Tests/Mocks/*.cs` - Mock implementations (MockNT8OrderAdapter)
## Strictly Forbidden Modifications
You MUST NOT modify any existing files in these locations:
### Core Interfaces and Models
- `src/NT8.Core/Common/**` - Existing interfaces and base models
- `src/NT8.Core/Risk/**` - Risk management system (completed)
- `src/NT8.Core/Sizing/**` - Position sizing system (completed)
- `src/NT8.Core/Logging/**` - Logging infrastructure
### Build Configuration
- `Directory.Build.props` - Global build properties
- `*.csproj` files - Project files (unless adding new files to OMS project)
- `.gitignore`
### Documentation (Read-Only)
- `nt8_phasing_plan.md`
- `nt8_dev_spec.md`
- `NT8_Integration_Guidelines_for_AI_Agents.md`
- `AI_Agent_Workflow_and_Code_Templates.md`
### NT8 Adapters
- `src/NT8.Adapters/**` - NT8 integration (future phase)
## New File Creation Rules
### When creating new files:
1. Use proper namespace: `NT8.Core.OMS` for implementation, `NT8.Core.Tests.OMS` for tests
2. Include XML documentation on all public members
3. Follow existing file naming patterns (PascalCase, descriptive names)
4. Add to appropriate project file if needed
### File naming examples:
`BasicOrderManager.cs` - Implementation class
`OrderModels.cs` - Model classes
`IOrderManager.cs` - Interface
`BasicOrderManagerTests.cs` - Test class
`MockNT8OrderAdapter.cs` - Mock for testing
## Verification
Before any file operation, ask yourself:
1. Is this file in an allowed directory?
2. Am I modifying an existing Core interface? (FORBIDDEN)
3. Am I creating a new file in the correct location?
If unsure, DO NOT proceed - ask for clarification first.

View File

@@ -0,0 +1,153 @@
# Project Context
You are working on the **NT8 SDK** - an institutional-grade trading SDK for NinjaTrader 8.
## Project Purpose
This is production trading software used for automated futures trading (ES, NQ, MES, MNQ, CL, GC). Code quality is critical because:
- Bugs can cause real financial losses
- System runs 24/5 during market hours
- Performance requirements are strict (<200ms latency)
- This is institutional-grade, not hobbyist code
## Current Phase: Phase 1 - Core Trading Loop
You are implementing the **OMS (Order Management System)** component.
### OMS Responsibilities
- Manage complete order lifecycle (Pending Working Filled/Cancelled)
- Thread-safe order tracking
- State machine enforcement
- Integration with NT8 platform
- Position flattening capability
### What OMS Does NOT Do (Other Components Handle)
- Risk validation (IRiskManager handles this)
- Position sizing (IPositionSizer handles this)
- Strategy logic (IStrategy handles this)
- Direct NT8 calls (NT8Adapter handles this)
## Architecture Overview
```
Strategy Layer (IStrategy)
↓ generates StrategyIntent
Risk Layer (IRiskManager)
↓ validates and produces RiskDecision
Sizing Layer (IPositionSizer)
↓ calculates contracts and produces SizingResult
OMS Layer (IOrderManager) ← YOU ARE HERE
↓ manages order lifecycle
NT8 Adapter Layer (INT8OrderAdapter)
↓ bridges to NinjaTrader 8
NinjaTrader 8 Platform
```
## Your Current Task
Implement the **Basic OMS** with these deliverables:
### Phase 1 Deliverables
1. `OrderModels.cs` - Order request/status models and enums
2. `IOrderManager.cs` - Core interface definition
3. `INT8OrderAdapter.cs` - Adapter interface
4. `BasicOrderManager.cs` - Implementation with state machine
5. `MockNT8OrderAdapter.cs` - Mock for testing
6. Unit tests - Comprehensive test coverage (>80%)
### Out of Scope (Future Phases)
- ❌ Partial fill aggregation (Phase 2)
- ❌ Retry logic (Phase 2)
- ❌ Position reconciliation (Phase 2)
- ❌ Advanced order types (Phase 3)
- ❌ Smart order routing (Phase 3)
## Key Design Principles
### 1. Risk-First Architecture
ALL trading operations flow through IRiskManager before OMS.
The pattern is: Strategy → Risk → Sizing → OMS → NT8
**NEVER bypass risk checks.**
### 2. State Machine Discipline
Order states follow strict transitions:
```
Pending → Working → PartiallyFilled → Filled
↓ ↓
Cancelled Cancelled
Rejected
```
Invalid transitions MUST be rejected and logged.
### 3. Thread Safety
This system will run with:
- Multiple NT8 callbacks firing simultaneously
- UI queries happening while orders process
- State changes from external events
ALL shared state MUST be protected with locks.
### 4. Performance Targets
- Order submission: <5ms (excluding NT8 adapter)
- State transition: <1ms
- Query operations: <1ms
- Overall tick-to-trade: <200ms
### 5. Determinism
Order processing must be deterministic for:
- Backtesting accuracy
- Replay debugging
- Audit trails
## Technology Constraints
### Language & Framework
- C# 5.0 syntax ONLY (no C# 6+)
- .NET Framework 4.8 (not .NET Core/5+/6+)
- Target: Windows desktop environment
### Libraries
- Newtonsoft.Json (for serialization)
- Microsoft.Extensions.Logging (for logging)
- Microsoft.Extensions.DependencyInjection (for DI)
- System.Text.Json (not available)
- Any .NET Core/5+/6+ libraries
### Testing
- xUnit for test framework
- FluentAssertions for assertions
- Bogus for test data generation (if needed)
- Mock adapters for isolation
## Reference Documents
You have access to these design documents:
- `OMS_Design_Specification.md` - Complete technical design
- `Kilocode_Implementation_Guide.md` - Step-by-step tasks
- `OMS_Test_Scenarios.md` - Comprehensive test cases
When uncertain about design decisions, reference these documents.
## Success Criteria
Your implementation is complete when:
- [ ] All 6 deliverables created
- [ ] `verify-build.bat` passes
- [ ] >80% test coverage
- [ ] All tests passing
- [ ] No C# 6+ syntax
- [ ] State machine validated
- [ ] Thread safety verified
- [ ] Performance targets met
- [ ] Integration points tested
- [ ] Documentation complete
## Communication
When you need clarification:
1. Check `OMS_Design_Specification.md` first
2. Check existing code patterns in `src/NT8.Core/Risk/` or `src/NT8.Core/Sizing/`
3. If still uncertain, ask before implementing
**Remember:** This is production trading code. When in doubt, ask rather than guess.

View File

@@ -0,0 +1,164 @@
# Verification Requirements
You MUST verify your work at each checkpoint to ensure code quality and prevent errors.
## After EVERY File Creation or Modification
### Step 1: Run Build Verification
```bash
.\verify-build.bat
```
**Expected Output:**
```
✅ All checks passed!
```
**If build fails:**
1. Read the error message carefully
2. Fix the error immediately
3. Re-run verify-build.bat
4. DO NOT proceed to next file until build passes
### Step 2: Verify File Location
Check that the file is in an allowed directory:
-`src/NT8.Core/OMS/` - Implementation files
-`tests/NT8.Core.Tests/OMS/` - Test files
-`tests/NT8.Core.Tests/Mocks/` - Mock files
- ❌ Anywhere else - STOP and ask
### Step 3: Check Syntax Compliance
Scan your code for forbidden patterns:
- ❌ No `$"..."` - Use `string.Format()`
- ❌ No `?.` or `?[` - Use explicit null checks
- ❌ No `=>` in properties/methods - Use full syntax
- ❌ No `nameof()` - Use string literals
## After Completing Each Class
### Step 4: Run Unit Tests (if applicable)
```bash
dotnet test tests\NT8.Core.Tests --filter "FullyQualifiedName~OMS"
```
**Expected Output:**
```
Passed! - Failed: 0, Passed: X
```
### Step 5: Review Against Checklist
- [ ] All public members have XML documentation
- [ ] All dictionary access uses `lock (_lock)`
- [ ] All public methods have try-catch
- [ ] All logging uses `string.Format()`
- [ ] No C# 6+ syntax anywhere
- [ ] File compiles without warnings
## After Completing Full Task
### Step 6: Comprehensive Build
```bash
dotnet build NT8-SDK.sln --configuration Release
```
### Step 7: Full Test Suite
```bash
dotnet test tests\NT8.Core.Tests --verbosity normal
```
### Step 8: Code Coverage (Optional but Recommended)
```bash
dotnet test tests\NT8.Core.Tests --collect:"XPlat Code Coverage"
```
**Target:** >80% coverage for new code
## Common Verification Failures
### "Feature 'string interpolation' is not available"
**Cause:** Used `$"text {var}"`
**Fix:** Replace with `string.Format("text {0}", var)`
### "Feature 'null-conditional operator' is not available"
**Cause:** Used `obj?.Property`
**Fix:** Replace with explicit null check
### "Cannot access member before initialization"
**Cause:** Used auto-property initializer
**Fix:** Move initialization to constructor
### Lock-related warnings
**Cause:** Dictionary access outside lock
**Fix:** Wrap in `lock (_lock) { ... }`
## Emergency Stop Conditions
STOP immediately and ask for help if:
1. ❌ Build fails with errors you don't understand
2. ❌ Tests fail unexpectedly after your changes
3. ❌ You need to modify files outside allowed directories
4. ❌ You're unsure about a design decision
5. ❌ Performance is severely degraded
## Verification Workflow Summary
```
Write Code
Run verify-build.bat
Build passes? → NO → Fix errors, repeat
↓ YES
Check syntax (no C# 6+)
Check patterns (locks, try-catch, logging)
Check documentation (XML docs)
Run unit tests (if applicable)
All pass? → NO → Fix tests, repeat
↓ YES
Mark file complete ✅
Move to next file
```
## Quality Gates
Your code MUST pass these gates before being considered complete:
### Gate 1: Compilation
-`verify-build.bat` outputs "All checks passed!"
- ✅ No compiler warnings
- ✅ All references resolve
### Gate 2: Syntax Compliance
- ✅ No C# 6+ features detected
- ✅ Only .NET Framework 4.8 APIs used
- ✅ Proper using statements
### Gate 3: Pattern Compliance
- ✅ Thread-safe operations
- ✅ Error handling present
- ✅ Logging at correct levels
- ✅ XML documentation complete
### Gate 4: Testing
- ✅ Unit tests written and passing
- ✅ Coverage >80% (target)
- ✅ Edge cases tested
## Self-Check Questions
Before marking a file complete, ask:
1. Does `verify-build.bat` pass?
2. Did I use any C# 6+ syntax?
3. Is all dictionary access inside locks?
4. Do all public methods have try-catch?
5. Does all logging use string.Format?
6. Do all public members have XML docs?
7. Are there unit tests for this code?
8. Do the tests pass?
**If any answer is "No" or "I'm not sure" → DO NOT PROCEED**