Files
nt8-sdk/docs/archive/completed-tasks/TASK-03-trailing-stop.md
mo c9041df36a 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
2026-07-13 08:38:25 -04:00

152 lines
5.3 KiB
Markdown

# 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