# 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.