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,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

View 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

View 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

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

View 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

View 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

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

View 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