[GAP-045/GAP-046]: risk envelope guards complete
- BasicRiskManager.cs: add sized per-position risk validation and startup validator - NT8StrategyBase.cs: fail fast on incoherent risk config and validate after sizing - BasicRiskManagerTests.cs: cover assertions, sized risk, property sweep, MNQ tables - docs/00-governance: record validation evidence and NQ SIM follow-up Build: clean | Tests: 535 passing; Core 446 passing | Deploy: backup 20260823_144817
This commit is contained in:
@@ -1652,6 +1652,8 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
_riskConfig,
|
||||
_sizingConfig);
|
||||
|
||||
ValidateStartupRiskConfiguration();
|
||||
|
||||
_riskManager = new BasicRiskManager(_logger, DailyLossLimit);
|
||||
_positionSizer = new BasicPositionSizer(_logger);
|
||||
_circuitBreaker = new ExecutionCircuitBreaker(
|
||||
@@ -1688,6 +1690,28 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
_currentSession = null;
|
||||
}
|
||||
|
||||
private void ValidateStartupRiskConfiguration()
|
||||
{
|
||||
string symbol = Instrument != null && Instrument.MasterInstrument != null
|
||||
? Instrument.MasterInstrument.Name
|
||||
: "UNKNOWN";
|
||||
double tickValue = 12.50;
|
||||
|
||||
if (Instrument != null && Instrument.MasterInstrument != null)
|
||||
tickValue = Instrument.MasterInstrument.TickSize * Instrument.MasterInstrument.PointValue;
|
||||
|
||||
RiskEnvelopeValidator.ValidateStartupConfiguration(
|
||||
symbol,
|
||||
tickValue,
|
||||
EnableTrailingDrawdown,
|
||||
AccountStartingBalance,
|
||||
MaxStopTicks,
|
||||
MaxTradeRisk,
|
||||
MinContracts,
|
||||
MaxContracts,
|
||||
DailyLossLimit);
|
||||
}
|
||||
|
||||
private void InitializeTrailingDrawdownState()
|
||||
{
|
||||
if (Account == null)
|
||||
@@ -1980,23 +2004,6 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
return;
|
||||
}
|
||||
|
||||
if (EnableVerboseLogging)
|
||||
Print(string.Format("[SDK] Validating intent: {0} {1}", intent.Side, intent.Symbol));
|
||||
|
||||
var riskDecision = _riskManager.ValidateOrder(intent, context, _riskConfig);
|
||||
if (!riskDecision.Allow)
|
||||
{
|
||||
if (EnableVerboseLogging)
|
||||
Print(string.Format("[SDK] Risk REJECTED: {0}", riskDecision.RejectReason));
|
||||
if (_logger != null)
|
||||
_logger.LogWarning("Intent rejected by risk manager: {0}", riskDecision.RejectReason);
|
||||
LogRejectRateLimited("MaxTradeRisk", string.Format("Risk manager rejected: {0}", riskDecision.RejectReason), Time[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (EnableVerboseLogging)
|
||||
Print(string.Format("[SDK] Risk approved"));
|
||||
|
||||
var sizingResult = _positionSizer.CalculateSize(intent, context, _sizingConfig);
|
||||
if (EnableVerboseLogging)
|
||||
{
|
||||
@@ -2014,6 +2021,26 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
return;
|
||||
}
|
||||
|
||||
if (EnableVerboseLogging)
|
||||
Print(string.Format("[SDK] Validating sized intent: {0} {1} Qty={2}", intent.Side, intent.Symbol, sizingResult.Contracts));
|
||||
|
||||
var basicRiskManager = _riskManager as BasicRiskManager;
|
||||
var riskDecision = basicRiskManager != null
|
||||
? basicRiskManager.ValidateOrder(intent, context, _riskConfig, sizingResult.Contracts)
|
||||
: _riskManager.ValidateOrder(intent, context, _riskConfig);
|
||||
if (!riskDecision.Allow)
|
||||
{
|
||||
if (EnableVerboseLogging)
|
||||
Print(string.Format("[SDK] Risk REJECTED: {0}", riskDecision.RejectReason));
|
||||
if (_logger != null)
|
||||
_logger.LogWarning("Intent rejected by risk manager: {0}", riskDecision.RejectReason);
|
||||
LogRejectRateLimited("MaxTradeRisk", string.Format("Risk manager rejected: {0}", riskDecision.RejectReason), Time[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (EnableVerboseLogging)
|
||||
Print(string.Format("[SDK] Risk approved"));
|
||||
|
||||
var request = new OmsOrderRequest();
|
||||
request.Symbol = intent.Symbol;
|
||||
request.Side = MapOrderSide(intent.Side);
|
||||
|
||||
@@ -43,10 +43,19 @@ namespace NT8.Core.Risk
|
||||
}
|
||||
|
||||
public RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext context, RiskConfig config)
|
||||
{
|
||||
return ValidateOrder(intent, context, config, 1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates a sized order against Tier 1 risk controls.
|
||||
/// </summary>
|
||||
public RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext context, RiskConfig config, int candidateContracts)
|
||||
{
|
||||
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");
|
||||
if (candidateContracts < 0) throw new ArgumentException("candidateContracts must be non-negative", "candidateContracts");
|
||||
|
||||
// GAP-003: Validate RiskPerTrade <= MaxTradeRisk at startup
|
||||
if (config.RiskPerTrade > config.MaxTradeRisk)
|
||||
@@ -100,14 +109,15 @@ namespace NT8.Core.Risk
|
||||
}
|
||||
|
||||
// Tier 1: Per-trade risk limit
|
||||
var tradeRisk = CalculateTradeRisk(intent, context);
|
||||
var tradeRisk = CalculateTradeRisk(intent, context, candidateContracts);
|
||||
if (tradeRisk > config.MaxTradeRisk)
|
||||
{
|
||||
_logger.LogWarning("Trade risk too high: {0:C} > {1:C}", tradeRisk, config.MaxTradeRisk);
|
||||
|
||||
var riskMetrics = new Dictionary<string, object>();
|
||||
riskMetrics.Add("trade_risk", tradeRisk);
|
||||
riskMetrics.Add("limit", config.MaxTradeRisk);
|
||||
var riskMetrics = new Dictionary<string, object>();
|
||||
riskMetrics.Add("trade_risk", tradeRisk);
|
||||
riskMetrics.Add("limit", config.MaxTradeRisk);
|
||||
riskMetrics.Add("contracts", candidateContracts);
|
||||
|
||||
return new RiskDecision(
|
||||
allow: false,
|
||||
@@ -158,11 +168,11 @@ namespace NT8.Core.Risk
|
||||
}
|
||||
}
|
||||
|
||||
private static double CalculateTradeRisk(StrategyIntent intent, StrategyContext context)
|
||||
private static double CalculateTradeRisk(StrategyIntent intent, StrategyContext context, int candidateContracts)
|
||||
{
|
||||
// Get tick value for symbol - this will be enhanced in later phases
|
||||
var tickValue = GetTickValue(intent.Symbol);
|
||||
return intent.StopTicks * tickValue;
|
||||
return intent.StopTicks * tickValue * candidateContracts;
|
||||
}
|
||||
|
||||
private static double GetTickValue(string symbol)
|
||||
@@ -180,6 +190,21 @@ namespace NT8.Core.Risk
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets supported symbols with their tick values.
|
||||
/// </summary>
|
||||
public static Dictionary<string, double> GetSupportedSymbols()
|
||||
{
|
||||
var symbols = new Dictionary<string, double>();
|
||||
symbols.Add("ES", 12.50);
|
||||
symbols.Add("MES", 1.25);
|
||||
symbols.Add("NQ", 5.00);
|
||||
symbols.Add("MNQ", 0.50);
|
||||
symbols.Add("CL", 10.00);
|
||||
symbols.Add("GC", 10.00);
|
||||
return symbols;
|
||||
}
|
||||
|
||||
private int GetOpenPositionCount()
|
||||
{
|
||||
// For Phase 0, return simplified count
|
||||
@@ -311,4 +336,67 @@ namespace NT8.Core.Risk
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates risk-envelope parameter pairs before realtime order flow starts.
|
||||
/// </summary>
|
||||
public static class RiskEnvelopeValidator
|
||||
{
|
||||
/// <summary>
|
||||
/// Throws when a risk-envelope parameter pair is internally inconsistent.
|
||||
/// </summary>
|
||||
public static void ValidateStartupConfiguration(
|
||||
string symbol,
|
||||
double tickValue,
|
||||
bool enableTrailingDrawdown,
|
||||
double accountStartingBalance,
|
||||
int maxStopTicks,
|
||||
double maxTradeRisk,
|
||||
int minContracts,
|
||||
int maxContracts,
|
||||
double dailyLossLimit)
|
||||
{
|
||||
if (string.IsNullOrEmpty(symbol))
|
||||
symbol = "UNKNOWN";
|
||||
|
||||
if (enableTrailingDrawdown && accountStartingBalance <= 0.0)
|
||||
{
|
||||
throw new ArgumentException(string.Format(
|
||||
"Invalid risk configuration for {0}: EnableTrailingDrawdown ({1}) requires AccountStartingBalance ({2:F2}) > 0.",
|
||||
symbol,
|
||||
enableTrailingDrawdown,
|
||||
accountStartingBalance));
|
||||
}
|
||||
|
||||
double maxStopRisk = maxStopTicks * tickValue;
|
||||
if (maxStopRisk > maxTradeRisk)
|
||||
{
|
||||
throw new ArgumentException(string.Format(
|
||||
"Invalid risk configuration for {0}: MaxStopTicks ({1}) * TickValue ({2:F2}) = {3:F2} cannot exceed MaxTradeRisk ({4:F2}).",
|
||||
symbol,
|
||||
maxStopTicks,
|
||||
tickValue,
|
||||
maxStopRisk,
|
||||
maxTradeRisk));
|
||||
}
|
||||
|
||||
if (minContracts < 1 || minContracts > maxContracts)
|
||||
{
|
||||
throw new ArgumentException(string.Format(
|
||||
"Invalid risk configuration for {0}: MinContracts ({1}) must be >= 1 and <= MaxContracts ({2}).",
|
||||
symbol,
|
||||
minContracts,
|
||||
maxContracts));
|
||||
}
|
||||
|
||||
if (maxTradeRisk > dailyLossLimit)
|
||||
{
|
||||
throw new ArgumentException(string.Format(
|
||||
"Invalid risk configuration for {0}: MaxTradeRisk ({1:F2}) cannot exceed DailyLossLimit ({2:F2}).",
|
||||
symbol,
|
||||
maxTradeRisk,
|
||||
dailyLossLimit));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user