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:
2026-07-13 08:38:25 -04:00
parent 99e993bee6
commit c9041df36a
64 changed files with 3338 additions and 825 deletions

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

View 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** ✅

View 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**

View 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** ✅

View 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** ✅

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

View 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**

View 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** ✅