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:
190
src/NT8.Core/Calendar/CmeHolidayCalendar.cs
Normal file
190
src/NT8.Core/Calendar/CmeHolidayCalendar.cs
Normal file
@@ -0,0 +1,190 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using NT8.Core.Logging;
|
||||
|
||||
namespace NT8.Core.Calendar
|
||||
{
|
||||
/// <summary>
|
||||
/// CME Holiday Calendar - determines if a given date is a CME holiday or early-close day.
|
||||
/// Covers standard US futures holidays observed by CME Group (CBOT, CME, COMEX, NYMEX).
|
||||
/// </summary>
|
||||
public static class CmeHolidayCalendar
|
||||
{
|
||||
private static readonly ILogger _logger = new BasicLogger("CmeHolidayCalendar");
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the given date is a CME full holiday (market closed all day).
|
||||
/// </summary>
|
||||
/// <param name="date">Date to check (date portion only).</param>
|
||||
/// <returns>True if CME holiday, false otherwise.</returns>
|
||||
public static bool IsHoliday(DateTime date)
|
||||
{
|
||||
var d = date.Date;
|
||||
int year = d.Year;
|
||||
|
||||
// Fixed-date holidays (observed on nearest weekday if weekend)
|
||||
if (IsObservedHoliday(d, year, 1, 1)) return true; // New Year's Day
|
||||
if (IsObservedHoliday(d, year, 7, 4)) return true; // Independence Day
|
||||
if (IsObservedHoliday(d, year, 12, 25)) return true; // Christmas Day
|
||||
|
||||
// Monday holidays (3rd Monday Jan, 3rd Monday Feb, last Monday May, 1st Monday Sep)
|
||||
if (IsNthWeekday(d, year, 1, DayOfWeek.Monday, 3)) return true; // MLK Jr. Day
|
||||
if (IsNthWeekday(d, year, 2, DayOfWeek.Monday, 3)) return true; // Presidents Day
|
||||
if (IsLastWeekday(d, year, 5, DayOfWeek.Monday)) return true; // Memorial Day
|
||||
if (IsNthWeekday(d, year, 9, DayOfWeek.Monday, 1)) return true; // Labor Day
|
||||
|
||||
// Thanksgiving: 4th Thursday November
|
||||
if (IsNthWeekday(d, year, 11, DayOfWeek.Thursday, 4)) return true;
|
||||
|
||||
// Good Friday (Friday before Easter)
|
||||
if (d == GetGoodFriday(year)) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the given date is a CME early-close day (market closes at 1:00 PM ET or 1:15 PM ET).
|
||||
/// </summary>
|
||||
/// <param name="date">Date to check.</param>
|
||||
/// <returns>True if early close, false otherwise.</returns>
|
||||
public static bool IsEarlyClose(DateTime date)
|
||||
{
|
||||
var d = date.Date;
|
||||
int year = d.Year;
|
||||
|
||||
// Day after Thanksgiving (Black Friday) - early close 1:00 PM ET
|
||||
var thanksgiving = GetNthWeekday(year, 11, DayOfWeek.Thursday, 4);
|
||||
if (d == thanksgiving.AddDays(1)) return true;
|
||||
|
||||
// Christmas Eve (Dec 24) - if not weekend, early close 1:15 PM ET
|
||||
if (IsObservedHoliday(d, year, 12, 24)) return true;
|
||||
|
||||
// New Year's Eve (Dec 31) - if not weekend, early close 1:15 PM ET
|
||||
if (IsObservedHoliday(d, year, 12, 31)) return true;
|
||||
|
||||
// Day before Independence Day (Jul 3) - if not weekend, early close
|
||||
if (IsObservedHoliday(d, year, 7, 3)) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the trading session type for a date: Regular, EarlyClose, or Closed.
|
||||
/// </summary>
|
||||
public static SessionType GetSessionType(DateTime date)
|
||||
{
|
||||
if (IsHoliday(date)) return SessionType.Closed;
|
||||
if (IsEarlyClose(date)) return SessionType.EarlyClose;
|
||||
return SessionType.Regular;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if strategy should skip ORB logic for this date.
|
||||
/// </summary>
|
||||
public static bool ShouldSkipOrbWindow(DateTime date)
|
||||
{
|
||||
return GetSessionType(date) != SessionType.Regular;
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────
|
||||
// Helpers
|
||||
// ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Checks if date matches a fixed holiday, with weekend observance rules.
|
||||
/// If holiday falls on Saturday, observed Friday. If Sunday, observed Monday.
|
||||
/// </summary>
|
||||
private static bool IsObservedHoliday(DateTime date, int year, int month, int day)
|
||||
{
|
||||
var actual = new DateTime(year, month, day);
|
||||
var observed = GetObservedDate(actual);
|
||||
return date == observed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the observed date for a fixed holiday (weekend -> nearest weekday).
|
||||
/// </summary>
|
||||
private static DateTime GetObservedDate(DateTime actual)
|
||||
{
|
||||
if (actual.DayOfWeek == DayOfWeek.Saturday)
|
||||
return actual.AddDays(-1); // Observed Friday
|
||||
if (actual.DayOfWeek == DayOfWeek.Sunday)
|
||||
return actual.AddDays(1); // Observed Monday
|
||||
return actual;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if date is the Nth occurrence of a weekday in a month (e.g., 3rd Monday).
|
||||
/// </summary>
|
||||
private static bool IsNthWeekday(DateTime date, int year, int month, DayOfWeek dow, int n)
|
||||
{
|
||||
var target = GetNthWeekday(year, month, dow, n);
|
||||
return date == target;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the Nth occurrence of a weekday in a month.
|
||||
/// </summary>
|
||||
private static DateTime GetNthWeekday(int year, int month, DayOfWeek dow, int n)
|
||||
{
|
||||
var first = new DateTime(year, month, 1);
|
||||
int offset = ((int)dow - (int)first.DayOfWeek + 7) % 7;
|
||||
var firstOccurrence = first.AddDays(offset);
|
||||
return firstOccurrence.AddDays(7 * (n - 1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if date is the last occurrence of a weekday in a month (e.g., last Monday).
|
||||
/// </summary>
|
||||
private static bool IsLastWeekday(DateTime date, int year, int month, DayOfWeek dow)
|
||||
{
|
||||
var target = GetLastWeekday(year, month, dow);
|
||||
return date == target;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the last occurrence of a weekday in a month.
|
||||
/// </summary>
|
||||
private static DateTime GetLastWeekday(int year, int month, DayOfWeek dow)
|
||||
{
|
||||
var lastDay = new DateTime(year, month, DateTime.DaysInMonth(year, month));
|
||||
int offset = ((int)lastDay.DayOfWeek - (int)dow + 7) % 7;
|
||||
return lastDay.AddDays(-offset);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes Good Friday for a given year using Anonymous Gregorian algorithm.
|
||||
/// </summary>
|
||||
private static DateTime GetGoodFriday(int year)
|
||||
{
|
||||
// Anonymous Gregorian algorithm for Easter Sunday
|
||||
int a = year % 19;
|
||||
int b = year / 100;
|
||||
int c = year % 100;
|
||||
int d = b / 4;
|
||||
int e = b % 4;
|
||||
int f = (b + 8) / 25;
|
||||
int g = (b - f + 1) / 3;
|
||||
int h = (19 * a + b - d - g + 15) % 30;
|
||||
int i = c / 4;
|
||||
int k = c % 4;
|
||||
int l = (32 + 2 * e + 2 * i - h - k) % 7;
|
||||
int m = (a + 11 * h + 22 * l) / 451;
|
||||
int month = (h + l - 7 * m + 114) / 31;
|
||||
int day = ((h + l - 7 * m + 114) % 31) + 1;
|
||||
|
||||
var easter = new DateTime(year, month, day);
|
||||
return easter.AddDays(-2); // Good Friday = 2 days before Easter
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enum for session type.
|
||||
/// </summary>
|
||||
public enum SessionType
|
||||
{
|
||||
Regular,
|
||||
EarlyClose,
|
||||
Closed
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,98 +4,105 @@ using System.Collections.Generic;
|
||||
namespace NT8.Core.Common.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Risk management configuration
|
||||
/// </summary>
|
||||
public class RiskConfig
|
||||
{
|
||||
// Phase 1 - Basic Risk Properties
|
||||
|
||||
/// <summary>
|
||||
/// Daily loss limit in dollars
|
||||
/// Risk management configuration
|
||||
/// </summary>
|
||||
public double DailyLossLimit { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Maximum risk per trade in dollars
|
||||
/// </summary>
|
||||
public double MaxTradeRisk { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Maximum number of open positions
|
||||
/// </summary>
|
||||
public int MaxOpenPositions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether emergency flatten is enabled
|
||||
/// </summary>
|
||||
public bool EmergencyFlattenEnabled { get; set; }
|
||||
|
||||
// Phase 2 - Advanced Risk Properties (Optional)
|
||||
|
||||
/// <summary>
|
||||
/// Weekly loss limit in dollars (optional, for advanced risk management)
|
||||
/// </summary>
|
||||
public double? WeeklyLossLimit { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Trailing drawdown limit in dollars (optional, for advanced risk management)
|
||||
/// </summary>
|
||||
public double? TrailingDrawdownLimit { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Maximum cross-strategy exposure in dollars (optional, for advanced risk management)
|
||||
/// </summary>
|
||||
public double? MaxCrossStrategyExposure { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Maximum correlated exposure in dollars (optional, for advanced risk management)
|
||||
/// </summary>
|
||||
public double? MaxCorrelatedExposure { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for RiskConfig (Phase 1 - backward compatible)
|
||||
/// </summary>
|
||||
public RiskConfig(
|
||||
double dailyLossLimit,
|
||||
double maxTradeRisk,
|
||||
int maxOpenPositions,
|
||||
bool emergencyFlattenEnabled)
|
||||
public class RiskConfig
|
||||
{
|
||||
DailyLossLimit = dailyLossLimit;
|
||||
MaxTradeRisk = maxTradeRisk;
|
||||
MaxOpenPositions = maxOpenPositions;
|
||||
EmergencyFlattenEnabled = emergencyFlattenEnabled;
|
||||
// Phase 1 - Basic Risk Properties
|
||||
|
||||
// Phase 2 properties default to null (not set)
|
||||
WeeklyLossLimit = null;
|
||||
TrailingDrawdownLimit = null;
|
||||
MaxCrossStrategyExposure = null;
|
||||
MaxCorrelatedExposure = null;
|
||||
}
|
||||
/// <summary>
|
||||
/// Daily loss limit in dollars
|
||||
/// </summary>
|
||||
public double DailyLossLimit { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for RiskConfig (Phase 2 - with advanced parameters)
|
||||
/// </summary>
|
||||
public RiskConfig(
|
||||
double dailyLossLimit,
|
||||
double maxTradeRisk,
|
||||
int maxOpenPositions,
|
||||
bool emergencyFlattenEnabled,
|
||||
double? weeklyLossLimit,
|
||||
double? trailingDrawdownLimit,
|
||||
double? maxCrossStrategyExposure,
|
||||
double? maxCorrelatedExposure)
|
||||
{
|
||||
DailyLossLimit = dailyLossLimit;
|
||||
MaxTradeRisk = maxTradeRisk;
|
||||
MaxOpenPositions = maxOpenPositions;
|
||||
EmergencyFlattenEnabled = emergencyFlattenEnabled;
|
||||
WeeklyLossLimit = weeklyLossLimit;
|
||||
TrailingDrawdownLimit = trailingDrawdownLimit;
|
||||
MaxCrossStrategyExposure = maxCrossStrategyExposure;
|
||||
MaxCorrelatedExposure = maxCorrelatedExposure;
|
||||
/// <summary>
|
||||
/// Maximum risk per trade in dollars
|
||||
/// </summary>
|
||||
public double MaxTradeRisk { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Risk per trade in dollars (for sizing)
|
||||
/// </summary>
|
||||
public double RiskPerTrade { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Maximum number of open positions
|
||||
/// </summary>
|
||||
public int MaxOpenPositions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether emergency flatten is enabled
|
||||
/// </summary>
|
||||
public bool EmergencyFlattenEnabled { get; set; }
|
||||
|
||||
// Phase 2 - Advanced Risk Properties (Optional)
|
||||
|
||||
/// <summary>
|
||||
/// Weekly loss limit in dollars (optional, for advanced risk management)
|
||||
/// </summary>
|
||||
public double? WeeklyLossLimit { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Trailing drawdown limit in dollars (optional, for advanced risk management)
|
||||
/// </summary>
|
||||
public double? TrailingDrawdownLimit { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Maximum cross-strategy exposure in dollars (optional, for advanced risk management)
|
||||
/// </summary>
|
||||
public double? MaxCrossStrategyExposure { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Maximum correlated exposure in dollars (optional, for advanced risk management)
|
||||
/// </summary>
|
||||
public double? MaxCorrelatedExposure { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for RiskConfig (Phase 1 - backward compatible)
|
||||
/// </summary>
|
||||
public RiskConfig(
|
||||
double dailyLossLimit,
|
||||
double maxTradeRisk,
|
||||
int maxOpenPositions,
|
||||
bool emergencyFlattenEnabled)
|
||||
{
|
||||
DailyLossLimit = dailyLossLimit;
|
||||
MaxTradeRisk = maxTradeRisk;
|
||||
MaxOpenPositions = maxOpenPositions;
|
||||
EmergencyFlattenEnabled = emergencyFlattenEnabled;
|
||||
RiskPerTrade = maxTradeRisk; // Default to MaxTradeRisk for backward compatibility
|
||||
|
||||
// Phase 2 properties default to null (not set)
|
||||
WeeklyLossLimit = null;
|
||||
TrailingDrawdownLimit = null;
|
||||
MaxCrossStrategyExposure = null;
|
||||
MaxCorrelatedExposure = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for RiskConfig (Phase 2 - with advanced parameters)
|
||||
/// </summary>
|
||||
public RiskConfig(
|
||||
double dailyLossLimit,
|
||||
double maxTradeRisk,
|
||||
int maxOpenPositions,
|
||||
bool emergencyFlattenEnabled,
|
||||
double? weeklyLossLimit,
|
||||
double? trailingDrawdownLimit,
|
||||
double? maxCrossStrategyExposure,
|
||||
double? maxCorrelatedExposure)
|
||||
{
|
||||
DailyLossLimit = dailyLossLimit;
|
||||
MaxTradeRisk = maxTradeRisk;
|
||||
MaxOpenPositions = maxOpenPositions;
|
||||
EmergencyFlattenEnabled = emergencyFlattenEnabled;
|
||||
RiskPerTrade = maxTradeRisk; // Default to MaxTradeRisk for backward compatibility
|
||||
WeeklyLossLimit = weeklyLossLimit;
|
||||
TrailingDrawdownLimit = trailingDrawdownLimit;
|
||||
MaxCrossStrategyExposure = maxCrossStrategyExposure;
|
||||
MaxCorrelatedExposure = maxCorrelatedExposure;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Position sizing configuration
|
||||
@@ -501,4 +508,35 @@ namespace NT8.Core.Common.Models
|
||||
ExecutionId = executionId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runner activation mode for position management
|
||||
/// </summary>
|
||||
public enum RunnerMode
|
||||
{
|
||||
/// <summary>
|
||||
/// Automatically resolve based on quantity: Qty>=2 => Mode1DualLeg, Qty=1 => Mode2RunnerOnly
|
||||
/// </summary>
|
||||
Auto,
|
||||
|
||||
/// <summary>
|
||||
/// Dual-leg: scaler leg with fixed target + runner leg with trailing stop
|
||||
/// </summary>
|
||||
Mode1DualLeg,
|
||||
|
||||
/// <summary>
|
||||
/// Runner-only: full position on trailing stop, no fixed target
|
||||
/// </summary>
|
||||
Mode2RunnerOnly,
|
||||
|
||||
/// <summary>
|
||||
/// Scaler-only: full position with fixed target, no runner
|
||||
/// </summary>
|
||||
Mode3ScalerOnly,
|
||||
|
||||
/// <summary>
|
||||
/// Disabled: original single-leg behavior, no runner
|
||||
/// </summary>
|
||||
Disabled
|
||||
}
|
||||
}
|
||||
@@ -401,42 +401,45 @@ namespace NT8.Core.Intelligence
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Daily bar data passed to ORB-specific factor calculators.
|
||||
/// Contains a lookback window of recent daily bars in chronological order,
|
||||
/// oldest first, with index [Count-1] being the most recent completed day.
|
||||
/// </summary>
|
||||
public struct DailyBarContext
|
||||
{
|
||||
/// <summary>Daily high prices, oldest first.</summary>
|
||||
public double[] Highs;
|
||||
/// Daily bar data passed to ORB-specific factor calculators.
|
||||
/// Contains a lookback window of recent daily bars in chronological order,
|
||||
/// oldest first, with index [Count-1] being the most recent completed day.
|
||||
/// </summary>
|
||||
public struct DailyBarContext
|
||||
{
|
||||
/// <summary>Daily high prices, oldest first.</summary>
|
||||
public double[] Highs;
|
||||
|
||||
/// <summary>Daily low prices, oldest first.</summary>
|
||||
public double[] Lows;
|
||||
/// <summary>Daily low prices, oldest first.</summary>
|
||||
public double[] Lows;
|
||||
|
||||
/// <summary>Daily close prices, oldest first.</summary>
|
||||
public double[] Closes;
|
||||
/// <summary>Daily close prices, oldest first.</summary>
|
||||
public double[] Closes;
|
||||
|
||||
/// <summary>Daily open prices, oldest first.</summary>
|
||||
public double[] Opens;
|
||||
/// <summary>Daily open prices, oldest first.</summary>
|
||||
public double[] Opens;
|
||||
|
||||
/// <summary>Daily volume values, oldest first.</summary>
|
||||
public long[] Volumes;
|
||||
/// <summary>Daily volume values, oldest first.</summary>
|
||||
public long[] Volumes;
|
||||
|
||||
/// <summary>Number of valid bars populated.</summary>
|
||||
public int Count;
|
||||
/// <summary>Number of valid bars populated.</summary>
|
||||
public int Count;
|
||||
|
||||
/// <summary>Today's RTH open price.</summary>
|
||||
public double TodayOpen;
|
||||
/// <summary>Today's RTH open price.</summary>
|
||||
public double TodayOpen;
|
||||
|
||||
/// <summary>Volume of the breakout bar (current intraday bar).</summary>
|
||||
public double BreakoutBarVolume;
|
||||
/// <summary>Volume of the breakout bar (current intraday bar).</summary>
|
||||
public double BreakoutBarVolume;
|
||||
|
||||
/// <summary>Average intraday volume per bar for today's session so far.</summary>
|
||||
public double AvgIntradayBarVolume;
|
||||
/// <summary>Average intraday volume per bar for today's session so far.</summary>
|
||||
public double AvgIntradayBarVolume;
|
||||
|
||||
/// <summary>Trade direction: 1 for long, -1 for short.</summary>
|
||||
public int TradeDirection;
|
||||
}
|
||||
/// <summary>Trade direction: 1 for long, -1 for short.</summary>
|
||||
public int TradeDirection;
|
||||
|
||||
/// <summary>ORB range in ticks (Factor 7: ORBvsATR).</summary>
|
||||
public double OrbRangeTicks;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scores the setup based on narrow range day concepts.
|
||||
|
||||
@@ -127,6 +127,13 @@ namespace NT8.Core.Risk
|
||||
return correlationCheck;
|
||||
}
|
||||
|
||||
// Tier 3.5: Portfolio Heat Control (GAP-019)
|
||||
var heatCheck = ValidatePortfolioHeat(intent, context);
|
||||
if (!heatCheck.Allow)
|
||||
{
|
||||
return heatCheck;
|
||||
}
|
||||
|
||||
// All checks passed - combine metrics
|
||||
var riskLevel = DetermineAdvancedRiskLevel();
|
||||
var combinedMetrics = CombineMetrics(basicDecision.RiskMetrics);
|
||||
@@ -384,6 +391,89 @@ namespace NT8.Core.Risk
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validate portfolio heat limit (Tier 3.5) - GAP-019
|
||||
/// Caps total open risk as % of account balance.
|
||||
/// </summary>
|
||||
private RiskDecision ValidatePortfolioHeat(StrategyIntent intent, StrategyContext context)
|
||||
{
|
||||
// Skip if MaxHeatPct is not configured (<= 0)
|
||||
if (_advancedConfig.MaxHeatPct <= 0)
|
||||
{
|
||||
return new RiskDecision(
|
||||
allow: true,
|
||||
rejectReason: null,
|
||||
modifiedIntent: null,
|
||||
riskLevel: RiskLevel.Low,
|
||||
riskMetrics: new Dictionary<string, object>()
|
||||
);
|
||||
}
|
||||
|
||||
double accountBalance = 0.0;
|
||||
if (context.Account != null)
|
||||
{
|
||||
accountBalance = context.Account.Equity;
|
||||
}
|
||||
|
||||
// If account balance is 0 or negative, skip the check (edge case)
|
||||
if (accountBalance <= 0)
|
||||
{
|
||||
_logger.LogWarning("Account balance is zero or negative, skipping heat check");
|
||||
return new RiskDecision(
|
||||
allow: true,
|
||||
rejectReason: null,
|
||||
modifiedIntent: null,
|
||||
riskLevel: RiskLevel.Low,
|
||||
riskMetrics: new Dictionary<string, object>()
|
||||
);
|
||||
}
|
||||
|
||||
// Calculate TotalOpenRisk from existing positions
|
||||
double totalOpenRisk = 0.0;
|
||||
foreach (var exposure in _state.ExposureBySymbol)
|
||||
{
|
||||
totalOpenRisk += Math.Abs(exposure.Value);
|
||||
}
|
||||
|
||||
// Calculate NewTradeRisk from intent
|
||||
var newTradeRisk = CalculateIntentExposure(intent, context);
|
||||
newTradeRisk = Math.Abs(newTradeRisk);
|
||||
|
||||
// Calculate HeatPct
|
||||
double heatPct = (totalOpenRisk + newTradeRisk) / accountBalance * 100.0;
|
||||
|
||||
// Log the heat check
|
||||
_logger.LogDebug("[SDK] Heat check: {0:F1}% of {1:F1}% limit", heatPct, _advancedConfig.MaxHeatPct);
|
||||
|
||||
if (heatPct > _advancedConfig.MaxHeatPct)
|
||||
{
|
||||
_logger.LogWarning("Portfolio heat {0:F1}% exceeds limit {1:F1}%", heatPct, _advancedConfig.MaxHeatPct);
|
||||
|
||||
var metrics = new Dictionary<string, object>();
|
||||
metrics.Add("heat_pct", heatPct);
|
||||
metrics.Add("heat_limit_pct", _advancedConfig.MaxHeatPct);
|
||||
metrics.Add("total_open_risk", totalOpenRisk);
|
||||
metrics.Add("new_trade_risk", newTradeRisk);
|
||||
metrics.Add("account_balance", accountBalance);
|
||||
|
||||
return new RiskDecision(
|
||||
allow: false,
|
||||
rejectReason: String.Format("Portfolio heat {0:F1}% exceeds limit {1:F1}%", heatPct, _advancedConfig.MaxHeatPct),
|
||||
modifiedIntent: null,
|
||||
riskLevel: RiskLevel.High,
|
||||
riskMetrics: metrics
|
||||
);
|
||||
}
|
||||
|
||||
return new RiskDecision(
|
||||
allow: true,
|
||||
rejectReason: null,
|
||||
modifiedIntent: null,
|
||||
riskLevel: RiskLevel.Low,
|
||||
riskMetrics: new Dictionary<string, object>()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculate exposure from intent
|
||||
/// </summary>
|
||||
@@ -801,8 +891,8 @@ namespace NT8.Core.Risk
|
||||
_advancedConfig = config;
|
||||
_lastConfigUpdate = DateTime.UtcNow;
|
||||
|
||||
_logger.LogInformation("Advanced risk config updated: WeeklyLimit={0:C}, DrawdownLimit={1:C}",
|
||||
config.WeeklyLossLimit, config.TrailingDrawdownLimit);
|
||||
_logger.LogInformation("Advanced risk config updated: WeeklyLimit={0:C}, DrawdownLimit={1:C}, MaxHeatPct={2:F1}%",
|
||||
config.WeeklyLossLimit, config.TrailingDrawdownLimit, config.MaxHeatPct);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -841,4 +931,4 @@ namespace NT8.Core.Risk
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,65 +54,74 @@ namespace NT8.Core.Risk
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents the configuration for advanced risk management.
|
||||
/// </summary>
|
||||
public class AdvancedRiskConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the maximum weekly loss limit.
|
||||
/// Represents the configuration for advanced risk management.
|
||||
/// </summary>
|
||||
public double WeeklyLossLimit { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the trailing drawdown limit.
|
||||
/// </summary>
|
||||
public double TrailingDrawdownLimit { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the maximum exposure allowed across all strategies.
|
||||
/// </summary>
|
||||
public double? MaxCrossStrategyExposure { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the duration of the cooldown period after a risk breach.
|
||||
/// </summary>
|
||||
public TimeSpan CooldownDuration { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the maximum correlated exposure across instruments.
|
||||
/// </summary>
|
||||
public double? MaxCorrelatedExposure { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of allowed trading time windows.
|
||||
/// </summary>
|
||||
public List<TradingTimeWindow> TradingTimeWindows { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AdvancedRiskConfig"/> class.
|
||||
/// </summary>
|
||||
/// <param name="weeklyLossLimit">The maximum weekly loss limit.</param>
|
||||
/// <param name="trailingDrawdownLimit">The trailing drawdown limit.</param>
|
||||
/// <param name="maxCrossStrategyExposure">The maximum exposure allowed across all strategies.</param>
|
||||
/// <param name="cooldownDuration">The duration of the cooldown period after a risk breach.</param>
|
||||
/// <param name="maxCorrelatedExposure">The maximum correlated exposure across instruments.</param>
|
||||
/// <param name="tradingTimeWindows">The list of allowed trading time windows.</param>
|
||||
public AdvancedRiskConfig(
|
||||
double weeklyLossLimit,
|
||||
double trailingDrawdownLimit,
|
||||
double? maxCrossStrategyExposure,
|
||||
TimeSpan cooldownDuration,
|
||||
double? maxCorrelatedExposure,
|
||||
List<TradingTimeWindow> tradingTimeWindows)
|
||||
public class AdvancedRiskConfig
|
||||
{
|
||||
WeeklyLossLimit = weeklyLossLimit;
|
||||
TrailingDrawdownLimit = trailingDrawdownLimit;
|
||||
MaxCrossStrategyExposure = maxCrossStrategyExposure;
|
||||
CooldownDuration = cooldownDuration;
|
||||
MaxCorrelatedExposure = maxCorrelatedExposure;
|
||||
TradingTimeWindows = tradingTimeWindows ?? new List<TradingTimeWindow>();
|
||||
/// <summary>
|
||||
/// Gets the maximum weekly loss limit.
|
||||
/// </summary>
|
||||
public double WeeklyLossLimit { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the trailing drawdown limit.
|
||||
/// </summary>
|
||||
public double TrailingDrawdownLimit { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the maximum exposure allowed across all strategies.
|
||||
/// </summary>
|
||||
public double? MaxCrossStrategyExposure { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the duration of the cooldown period after a risk breach.
|
||||
/// </summary>
|
||||
public TimeSpan CooldownDuration { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the maximum correlated exposure across instruments.
|
||||
/// </summary>
|
||||
public double? MaxCorrelatedExposure { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of allowed trading time windows.
|
||||
/// </summary>
|
||||
public List<TradingTimeWindow> TradingTimeWindows { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the maximum portfolio heat percentage (Tier 3.5).
|
||||
/// Total open risk + new trade risk as % of account balance.
|
||||
/// </summary>
|
||||
public double MaxHeatPct { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AdvancedRiskConfig"/> class.
|
||||
/// </summary>
|
||||
/// <param name="weeklyLossLimit">The maximum weekly loss limit.</param>
|
||||
/// <param name="trailingDrawdownLimit">The trailing drawdown limit.</param>
|
||||
/// <param name="maxCrossStrategyExposure">The maximum exposure allowed across all strategies.</param>
|
||||
/// <param name="cooldownDuration">The duration of the cooldown period after a risk breach.</param>
|
||||
/// <param name="maxCorrelatedExposure">The maximum correlated exposure across instruments.</param>
|
||||
/// <param name="tradingTimeWindows">The list of allowed trading time windows.</param>
|
||||
/// <param name="maxHeatPct">Maximum portfolio heat percentage (default 3.0).</param>
|
||||
public AdvancedRiskConfig(
|
||||
double weeklyLossLimit,
|
||||
double trailingDrawdownLimit,
|
||||
double? maxCrossStrategyExposure,
|
||||
TimeSpan cooldownDuration,
|
||||
double? maxCorrelatedExposure,
|
||||
List<TradingTimeWindow> tradingTimeWindows,
|
||||
double maxHeatPct = 3.0)
|
||||
{
|
||||
WeeklyLossLimit = weeklyLossLimit;
|
||||
TrailingDrawdownLimit = trailingDrawdownLimit;
|
||||
MaxCrossStrategyExposure = maxCrossStrategyExposure;
|
||||
CooldownDuration = cooldownDuration;
|
||||
MaxCorrelatedExposure = maxCorrelatedExposure;
|
||||
TradingTimeWindows = tradingTimeWindows ?? new List<TradingTimeWindow>();
|
||||
MaxHeatPct = maxHeatPct;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents the current state of advanced risk management.
|
||||
|
||||
@@ -8,44 +8,59 @@ using System.Threading.Tasks;
|
||||
namespace NT8.Core.Risk
|
||||
{
|
||||
/// <summary>
|
||||
/// Basic risk manager implementing Tier 1 risk controls
|
||||
/// Thread-safe implementation using locks for state consistency
|
||||
/// </summary>
|
||||
public class BasicRiskManager : IRiskManager
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly object _lock = new object();
|
||||
|
||||
// Risk state - protected by _lock
|
||||
private double _dailyPnL;
|
||||
private double _maxDrawdown;
|
||||
private bool _tradingHalted;
|
||||
private double _configuredDailyLossLimit;
|
||||
private DateTime _lastUpdate = DateTime.UtcNow;
|
||||
private readonly Dictionary<string, double> _symbolExposure = new Dictionary<string, double>();
|
||||
|
||||
public BasicRiskManager(ILogger logger)
|
||||
/// Basic risk manager implementing Tier 1 risk controls
|
||||
/// Thread-safe implementation using locks for state consistency
|
||||
/// </summary>
|
||||
public class BasicRiskManager : IRiskManager
|
||||
{
|
||||
if (logger == null) throw new ArgumentNullException("logger");
|
||||
_logger = logger;
|
||||
_configuredDailyLossLimit = 1000.0;
|
||||
}
|
||||
private readonly ILogger _logger;
|
||||
private readonly object _lock = new object();
|
||||
|
||||
public BasicRiskManager(ILogger logger, double dailyLossLimit)
|
||||
{
|
||||
if (logger == null) throw new ArgumentNullException("logger");
|
||||
if (dailyLossLimit <= 0.0) throw new ArgumentException("dailyLossLimit must be positive", "dailyLossLimit");
|
||||
_logger = logger;
|
||||
_configuredDailyLossLimit = dailyLossLimit;
|
||||
}
|
||||
// Risk state - protected by _lock
|
||||
private double _dailyPnL;
|
||||
private double _maxDrawdown;
|
||||
private bool _tradingHalted;
|
||||
private double _configuredDailyLossLimit;
|
||||
private double _currentDailyLossLimit;
|
||||
private DateTime _lastUpdate = DateTime.UtcNow;
|
||||
private readonly Dictionary<string, double> _symbolExposure = new Dictionary<string, double>();
|
||||
|
||||
public BasicRiskManager(ILogger logger)
|
||||
{
|
||||
if (logger == null) throw new ArgumentNullException("logger");
|
||||
_logger = logger;
|
||||
_configuredDailyLossLimit = 1000.0;
|
||||
_currentDailyLossLimit = 1000.0;
|
||||
}
|
||||
|
||||
public BasicRiskManager(ILogger logger, double dailyLossLimit)
|
||||
{
|
||||
if (logger == null) throw new ArgumentNullException("logger");
|
||||
if (dailyLossLimit <= 0.0) throw new ArgumentException("dailyLossLimit must be positive", "dailyLossLimit");
|
||||
_logger = logger;
|
||||
_configuredDailyLossLimit = dailyLossLimit;
|
||||
_currentDailyLossLimit = dailyLossLimit;
|
||||
}
|
||||
|
||||
public RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext context, RiskConfig config)
|
||||
{
|
||||
if (intent == null) throw new ArgumentNullException("intent");
|
||||
if (context == null) throw new ArgumentNullException("context");
|
||||
if (config == null) throw new ArgumentNullException("config");
|
||||
{
|
||||
if (intent == null) throw new ArgumentNullException("intent");
|
||||
if (context == null) throw new ArgumentNullException("context");
|
||||
if (config == null) throw new ArgumentNullException("config");
|
||||
|
||||
lock (_lock)
|
||||
// GAP-003: Validate RiskPerTrade <= MaxTradeRisk at startup
|
||||
if (config.RiskPerTrade > config.MaxTradeRisk)
|
||||
{
|
||||
throw new System.ArgumentException(string.Format(
|
||||
"Invalid RiskConfig: RiskPerTrade ({0}) cannot exceed MaxTradeRisk ({1}). " +
|
||||
"Increase MaxTradeRisk or reduce RiskPerTrade.",
|
||||
config.RiskPerTrade, config.MaxTradeRisk));
|
||||
}
|
||||
|
||||
// Store the daily loss limit from config for GetRiskStatus
|
||||
_currentDailyLossLimit = config.DailyLossLimit;
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
// Check if trading is halted
|
||||
if (_tradingHalted)
|
||||
@@ -268,14 +283,14 @@ namespace NT8.Core.Risk
|
||||
alerts.Add(String.Format("Large drawdown: {0:C}", _maxDrawdown));
|
||||
|
||||
return new RiskStatus(
|
||||
tradingEnabled: !_tradingHalted,
|
||||
dailyPnL: _dailyPnL,
|
||||
dailyLossLimit: 1000, // Will come from config in Phase 1
|
||||
maxDrawdown: _maxDrawdown,
|
||||
openPositions: GetOpenPositionCount(),
|
||||
lastUpdate: _lastUpdate,
|
||||
activeAlerts: alerts
|
||||
);
|
||||
tradingEnabled: !_tradingHalted,
|
||||
dailyPnL: _dailyPnL,
|
||||
dailyLossLimit: _currentDailyLossLimit,
|
||||
maxDrawdown: _maxDrawdown,
|
||||
openPositions: GetOpenPositionCount(),
|
||||
lastUpdate: _lastUpdate,
|
||||
activeAlerts: alerts
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user