syntax = "proto3";

package risk;

// Risk Management Service provides comprehensive risk assessment, monitoring, and control capabilities
// for high-frequency trading operations. This service integrates real-time VaR calculations,
// position risk analysis, compliance monitoring, and emergency controls.
service RiskService {
  // Value at Risk (VaR) Calculations
  // Calculate current portfolio VaR using specified method and parameters
  rpc GetVaR(GetVaRRequest) returns (GetVaRResponse);
  
  // Stream real-time VaR updates as market conditions change
  rpc StreamVaRUpdates(StreamVaRRequest) returns (stream VaREvent);

  // Position Risk Analysis
  // Get comprehensive risk analysis for current positions
  rpc GetPositionRisk(GetPositionRiskRequest) returns (GetPositionRiskResponse);
  
  // Validate order against risk limits before execution
  rpc ValidateOrder(ValidateOrderRequest) returns (ValidateOrderResponse);

  // Risk Metrics and Monitoring
  // Get comprehensive portfolio risk metrics and statistics
  rpc GetRiskMetrics(GetRiskMetricsRequest) returns (GetRiskMetricsResponse);
  
  // Stream real-time risk alerts and violations
  rpc StreamRiskAlerts(StreamRiskAlertsRequest) returns (stream RiskAlertEvent);

  // Emergency Controls and Circuit Breakers
  // Trigger emergency stop to halt trading activities
  rpc EmergencyStop(EmergencyStopRequest) returns (EmergencyStopResponse);
  
  // Get status of all circuit breakers and safety mechanisms
  rpc GetCircuitBreakerStatus(GetCircuitBreakerStatusRequest) returns (GetCircuitBreakerStatusResponse);

  // Server-streaming: polls GetCircuitBreakerStatus at gateway level
  rpc StreamCircuitBreakerStatus(StreamCircuitBreakerStatusRequest) returns (stream GetCircuitBreakerStatusResponse);

  // Server-streaming: polls GetRiskMetrics at gateway level
  rpc StreamRiskMetrics(StreamRiskMetricsRequest) returns (stream GetRiskMetricsResponse);
}

// Streaming request messages

message StreamCircuitBreakerStatusRequest {
  optional string symbol = 1;   // Filter by symbol (all if not specified)
  uint32 interval_seconds = 2;  // 0 = server default (2s)
}

message StreamRiskMetricsRequest {
  optional string portfolio_id = 1; // Portfolio identifier (default if not specified)
  uint32 interval_seconds = 2;      // 0 = server default (3s)
}

// VaR (Value at Risk) Messages

// Request to calculate portfolio VaR
message GetVaRRequest {
  repeated string symbols = 1;          // Symbols to include in VaR calculation (empty = all positions)
  double confidence_level = 2;          // Confidence level (e.g., 0.95 for 95% VaR)
  int32 lookback_days = 3;              // Historical data period for calculation
  VaRMethod method = 4;                 // VaR calculation method (historical, parametric, Monte Carlo)
}

// Response containing VaR calculation results
message GetVaRResponse {
  double portfolio_var = 1;             // Total portfolio VaR value
  repeated SymbolVaR symbol_vars = 2;   // Individual symbol VaR contributions
  double confidence_level = 3;          // Confidence level used in calculation
  int32 lookback_days = 4;              // Historical period used
  VaRMethod method = 5;                 // Calculation method used
  int64 calculated_at = 6;              // Calculation timestamp (nanoseconds)
}

// Request to stream real-time VaR updates
message StreamVaRRequest {
  double confidence_level = 1;          // Confidence level for VaR calculation
  int32 update_frequency_seconds = 2;   // How often to send updates
}

// VaR contribution for a specific symbol
message SymbolVaR {
  string symbol = 1;                    // Trading symbol
  double var_value = 2;                 // VaR value for this symbol
  double position_size = 3;             // Current position size
  double contribution_pct = 4;          // Percentage contribution to total portfolio VaR
}

// Position Risk Analysis Messages

// Request for position risk analysis
message GetPositionRiskRequest {
  optional string symbol = 1;           // Filter by symbol (all symbols if not specified)
  optional string account_id = 2;       // Filter by account (all accounts if not specified)
}

// Response containing position risk analysis
message GetPositionRiskResponse {
  repeated PositionRisk position_risks = 1; // Risk analysis for each position
  double portfolio_risk_score = 2;      // Overall portfolio risk score (0-100)
}

// Request to validate order against risk limits
message ValidateOrderRequest {
  string symbol = 1;                    // Trading symbol
  double quantity = 2;                  // Order quantity
  double price = 3;                     // Order price
  string side = 4;                      // Buy or sell
  string account_id = 5;                // Trading account
}

// Response containing order validation results
message ValidateOrderResponse {
  bool is_valid = 1;                    // True if order passes all risk checks
  repeated RiskViolation violations = 2; // List of risk violations (if any)
  RiskScore risk_score = 3;             // Risk assessment for this order
  string message = 4;                   // Human-readable validation message
}

// Risk Metrics and Monitoring Messages

// Request for comprehensive risk metrics
message GetRiskMetricsRequest {
  optional string portfolio_id = 1;     // Portfolio identifier (default portfolio if not specified)
}

// Response containing comprehensive risk metrics
message GetRiskMetricsResponse {
  RiskMetrics metrics = 1;              // Complete risk metrics and statistics
  int64 calculated_at = 2;              // Metrics calculation timestamp (nanoseconds)
}

// Request to stream real-time risk alerts
message StreamRiskAlertsRequest {
  RiskAlertSeverity min_severity = 1;   // Minimum alert severity to receive
  repeated RiskAlertType alert_types = 2; // Types of alerts to receive (empty = all types)
}

// Emergency Control Messages

// Request to trigger emergency stop
message EmergencyStopRequest {
  EmergencyStopType stop_type = 1;      // Type of emergency stop (all trading, symbol, account, etc.)
  string reason = 2;                    // Reason for emergency stop
  optional string symbol = 3;           // Symbol to stop (for symbol-specific stops)
  optional string account_id = 4;       // Account to stop (for account-specific stops)
}

// Response after emergency stop execution
message EmergencyStopResponse {
  bool success = 1;                     // True if emergency stop was successful
  string message = 2;                   // Status message or error description
  int64 timestamp = 3;                  // Emergency stop timestamp (nanoseconds)
  repeated string affected_orders = 4;  // List of order IDs affected by the stop
}

// Request for circuit breaker status
message GetCircuitBreakerStatusRequest {
  optional string symbol = 1;           // Filter by symbol (all symbols if not specified)
}

// Response containing circuit breaker status
message GetCircuitBreakerStatusResponse {
  repeated CircuitBreakerStatus circuit_breakers = 1; // Status of all circuit breakers
}

// Core Risk Data Types

// Risk analysis for a specific position
message PositionRisk {
  string symbol = 1;                    // Trading symbol
  double position_size = 2;             // Current position size
  double market_value = 3;              // Market value of position
  double var_contribution = 4;          // Contribution to portfolio VaR
  double concentration_risk = 5;        // Position concentration risk (0-100)
  double liquidity_risk = 6;            // Liquidity risk score (0-100)
  RiskScore overall_score = 7;          // Overall risk assessment
  repeated RiskMetric metrics = 8;      // Additional risk metrics
}

message RiskViolation {
  RiskViolationType violation_type = 1;
  string description = 2;
  double current_value = 3;
  double limit_value = 4;
  RiskAlertSeverity severity = 5;
}

message RiskScore {
  double overall_score = 1;
  double concentration_score = 2;
  double liquidity_score = 3;
  double volatility_score = 4;
  double correlation_score = 5;
  RiskLevel risk_level = 6;
}

message RiskMetrics {
  double portfolio_var_1d = 1;
  double portfolio_var_5d = 2;
  double portfolio_var_30d = 3;
  double max_drawdown = 4;
  double current_drawdown = 5;
  double sharpe_ratio = 6;
  double sortino_ratio = 7;
  double beta = 8;
  double alpha = 9;
  double volatility = 10;
  repeated PositionRisk position_risks = 11;
}

message RiskMetric {
  string name = 1;
  double value = 2;
  string unit = 3;
  RiskLevel risk_level = 4;
}

message CircuitBreakerStatus {
  string name = 1;
  bool is_triggered = 2;
  optional string trigger_reason = 3;
  optional int64 triggered_at = 4;
  optional int64 reset_at = 5;
  CircuitBreakerType breaker_type = 6;
}

// Event Messages
message VaREvent {
  double portfolio_var = 1;
  repeated SymbolVaR symbol_vars = 2;
  VaRChangeType change_type = 3;
  int64 timestamp = 4;
}

message RiskAlertEvent {
  string alert_id = 1;
  RiskAlertType alert_type = 2;
  RiskAlertSeverity severity = 3;
  string message = 4;
  optional string symbol = 5;
  optional string account_id = 6;
  map<string, string> metadata = 7;
  int64 timestamp = 8;
}

// Enums

// VaR calculation methodology
enum VaRMethod {
  VAR_METHOD_UNSPECIFIED = 0;          // Default/unknown method
  VAR_METHOD_HISTORICAL = 1;           // Historical simulation method
  VAR_METHOD_PARAMETRIC = 2;           // Parametric (variance-covariance) method
  VAR_METHOD_MONTE_CARLO = 3;          // Monte Carlo simulation method
}

enum RiskViolationType {
  RISK_VIOLATION_TYPE_UNSPECIFIED = 0;
  RISK_VIOLATION_TYPE_POSITION_LIMIT = 1;
  RISK_VIOLATION_TYPE_CONCENTRATION = 2;
  RISK_VIOLATION_TYPE_VAR_LIMIT = 3;
  RISK_VIOLATION_TYPE_DRAWDOWN = 4;
  RISK_VIOLATION_TYPE_LIQUIDITY = 5;
  RISK_VIOLATION_TYPE_CORRELATION = 6;
}

// Risk assessment levels
enum RiskLevel {
  RISK_LEVEL_UNSPECIFIED = 0;          // Default/unknown level
  RISK_LEVEL_LOW = 1;                  // Low risk (green)
  RISK_LEVEL_MEDIUM = 2;               // Medium risk (yellow)
  RISK_LEVEL_HIGH = 3;                 // High risk (orange)
  RISK_LEVEL_CRITICAL = 4;             // Critical risk (red)
}

// Severity levels for risk alerts
enum RiskAlertSeverity {
  RISK_ALERT_SEVERITY_UNSPECIFIED = 0; // Default/unknown severity
  RISK_ALERT_SEVERITY_INFO = 1;        // Informational alert
  RISK_ALERT_SEVERITY_WARNING = 2;     // Warning alert
  RISK_ALERT_SEVERITY_CRITICAL = 3;    // Critical alert requiring attention
  RISK_ALERT_SEVERITY_EMERGENCY = 4;   // Emergency alert requiring immediate action
}

// Types of risk alerts
enum RiskAlertType {
  RISK_ALERT_TYPE_UNSPECIFIED = 0;     // Default/unknown type
  RISK_ALERT_TYPE_VAR_BREACH = 1;      // VaR limit breach
  RISK_ALERT_TYPE_POSITION_LIMIT = 2;  // Position size limit breach
  RISK_ALERT_TYPE_DRAWDOWN = 3;        // Drawdown limit breach
  RISK_ALERT_TYPE_CONCENTRATION = 4;   // Portfolio concentration risk
  RISK_ALERT_TYPE_LIQUIDITY = 5;       // Liquidity risk alert
  RISK_ALERT_TYPE_CORRELATION = 6;     // Correlation risk alert
}

// Types of emergency stops
enum EmergencyStopType {
  EMERGENCY_STOP_TYPE_UNSPECIFIED = 0; // Default/unknown type
  EMERGENCY_STOP_TYPE_ALL_TRADING = 1; // Stop all trading activity
  EMERGENCY_STOP_TYPE_SYMBOL = 2;      // Stop trading for specific symbol
  EMERGENCY_STOP_TYPE_ACCOUNT = 3;     // Stop trading for specific account
  EMERGENCY_STOP_TYPE_STRATEGY = 4;    // Stop specific trading strategy
}

enum CircuitBreakerType {
  CIRCUIT_BREAKER_TYPE_UNSPECIFIED = 0;
  CIRCUIT_BREAKER_TYPE_PORTFOLIO_LOSS = 1;
  CIRCUIT_BREAKER_TYPE_SYMBOL_VOLATILITY = 2;
  CIRCUIT_BREAKER_TYPE_POSITION_SIZE = 3;
  CIRCUIT_BREAKER_TYPE_DRAWDOWN = 4;
}

enum VaRChangeType {
  VAR_CHANGE_TYPE_UNSPECIFIED = 0;
  VAR_CHANGE_TYPE_INCREASED = 1;
  VAR_CHANGE_TYPE_DECREASED = 2;
  VAR_CHANGE_TYPE_BREACH = 3;
}