syntax = "proto3";

package foxhunt.tli;

// TLI Trading Service provides a unified client interface for all HFT trading operations.
// This service integrates trading, risk management, monitoring, and configuration capabilities
// into a single comprehensive API for the Terminal Line Interface (TLI) client application.
service TradingService {
  // Core Trading Operations
  // Submit a new trading order with validation
  rpc SubmitOrder(SubmitOrderRequest) returns (SubmitOrderResponse);
  
  // Cancel an existing order by ID
  rpc CancelOrder(CancelOrderRequest) returns (CancelOrderResponse);
  
  // Get current status of a specific order
  rpc GetOrderStatus(GetOrderStatusRequest) returns (GetOrderStatusResponse);
  
  // Get account information and balances
  rpc GetAccountInfo(GetAccountInfoRequest) returns (GetAccountInfoResponse);
  
  // Get current portfolio positions
  rpc GetPositions(GetPositionsRequest) returns (GetPositionsResponse);
  
  // Subscribe to real-time market data feeds
  rpc SubscribeMarketData(SubscribeMarketDataRequest) returns (stream MarketDataEvent);
  
  // Subscribe to real-time order status updates
  rpc SubscribeOrderUpdates(SubscribeOrderUpdatesRequest) returns (stream OrderUpdateEvent);

  // Integrated Risk Management
  // Calculate portfolio Value at Risk (VaR)
  rpc GetVaR(GetVaRRequest) returns (GetVaRResponse);
  
  // Analyze position-level risk exposure
  rpc GetPositionRisk(GetPositionRiskRequest) returns (GetPositionRiskResponse);
  
  // Validate order against risk limits before submission
  rpc ValidateOrder(ValidateOrderRequest) returns (ValidateOrderResponse);
  
  // Get comprehensive portfolio risk metrics
  rpc GetRiskMetrics(GetRiskMetricsRequest) returns (GetRiskMetricsResponse);
  
  // Subscribe to real-time risk alerts and violations
  rpc SubscribeRiskAlerts(SubscribeRiskAlertsRequest) returns (stream RiskAlertEvent);
  
  // Emergency stop with immediate trading halt
  rpc EmergencyStop(EmergencyStopRequest) returns (EmergencyStopResponse);

  // Integrated System Monitoring
  // Get system performance metrics
  rpc GetMetrics(GetMetricsRequest) returns (GetMetricsResponse);
  
  // Get latency performance statistics
  rpc GetLatency(GetLatencyRequest) returns (GetLatencyResponse);
  
  // Get throughput and capacity metrics
  rpc GetThroughput(GetThroughputRequest) returns (GetThroughputResponse);
  
  // Subscribe to real-time performance metrics
  rpc SubscribeMetrics(SubscribeMetricsRequest) returns (stream MetricsEvent);

  // Integrated Configuration Management
  // Update system parameters and settings
  rpc UpdateParameters(UpdateParametersRequest) returns (UpdateParametersResponse);
  
  // Get current configuration values
  rpc GetConfig(GetConfigRequest) returns (GetConfigResponse);
  
  // Subscribe to configuration changes
  rpc SubscribeConfig(SubscribeConfigRequest) returns (stream ConfigEvent);

  // Integrated System Health Monitoring
  // Get overall system health and service status
  rpc GetSystemStatus(GetSystemStatusRequest) returns (GetSystemStatusResponse);

  // Subscribe to system status changes and alerts
  rpc SubscribeSystemStatus(SubscribeSystemStatusRequest) returns (stream SystemStatusEvent);

  // ML Trading Operations
  // Submit ML-powered trading order with ensemble predictions
  rpc SubmitMLOrder(SubmitMLOrderRequest) returns (SubmitMLOrderResponse);

  // Get ML prediction history with outcomes
  rpc GetMLPredictions(GetMLPredictionsRequest) returns (GetMLPredictionsResponse);

  // Get ML model performance metrics
  rpc GetMLPerformance(GetMLPerformanceRequest) returns (GetMLPerformanceResponse);

  // Wave D: Regime Detection Operations
  // Get current regime state for a symbol
  rpc GetRegimeState(GetRegimeStateRequest) returns (GetRegimeStateResponse);

  // Get regime transition history for a symbol
  rpc GetRegimeTransitions(GetRegimeTransitionsRequest) returns (GetRegimeTransitionsResponse);
}

// Order submission request
message SubmitOrderRequest {
  string symbol = 1;
  OrderSide side = 2;
  OrderType order_type = 3;
  double quantity = 4;
  optional double price = 5;
  optional double stop_price = 6;
  string time_in_force = 7;
  string client_order_id = 8;
}

// Order submission response
message SubmitOrderResponse {
  bool success = 1;
  string order_id = 2;
  string message = 3;
  int64 timestamp_unix_nanos = 4;
}

// Order cancellation request
message CancelOrderRequest {
  string order_id = 1;
  string symbol = 2;
}

// Order cancellation response
message CancelOrderResponse {
  bool success = 1;
  string message = 2;
  int64 timestamp_unix_nanos = 3;
}

// Order status request
message GetOrderStatusRequest {
  string order_id = 1;
}

// Order status response
message GetOrderStatusResponse {
  string order_id = 1;
  string symbol = 2;
  OrderSide side = 3;
  OrderType order_type = 4;
  double quantity = 5;
  double filled_quantity = 6;
  double remaining_quantity = 7;
  double average_price = 8;
  OrderStatus status = 9;
  int64 created_at_unix_nanos = 10;
  int64 updated_at_unix_nanos = 11;
}

// Account information request
message GetAccountInfoRequest {
  string account_id = 1;
}

// Account information response
message GetAccountInfoResponse {
  string account_id = 1;
  double total_value = 2;
  double cash_balance = 3;
  double buying_power = 4;
  double maintenance_margin = 5;
  double day_trading_buying_power = 6;
}

// Positions request
message GetPositionsRequest {
  optional string symbol = 1; // Filter by symbol if provided
}

// Positions response
message GetPositionsResponse {
  repeated Position positions = 1;
}

// Position information
message Position {
  string symbol = 1;
  double quantity = 2;
  double market_price = 3;
  double market_value = 4;
  double average_cost = 5;
  double unrealized_pnl = 6;
  double realized_pnl = 7;
}

// Market data subscription request
message SubscribeMarketDataRequest {
  repeated string symbols = 1;
  repeated MarketDataType data_types = 2;
}

// Market data event
message MarketDataEvent {
  oneof event {
    TickData tick = 1;
    QuoteData quote = 2;
    TradeData trade = 3;
    BarData bar = 4;
  }
}

// Tick data
message TickData {
  string symbol = 1;
  int64 timestamp_unix_nanos = 2;
  double price = 3;
  uint64 size = 4;
  string exchange = 5;
}

// Quote data
message QuoteData {
  string symbol = 1;
  int64 timestamp_unix_nanos = 2;
  double bid_price = 3;
  uint64 bid_size = 4;
  double ask_price = 5;
  uint64 ask_size = 6;
  string exchange = 7;
}

// Trade data
message TradeData {
  string symbol = 1;
  int64 timestamp_unix_nanos = 2;
  double price = 3;
  uint64 size = 4;
  string trade_id = 5;
  string exchange = 6;
}

// Bar data
message BarData {
  string symbol = 1;
  int64 timestamp_unix_nanos = 2;
  string timeframe = 3;
  double open = 4;
  double high = 5;
  double low = 6;
  double close = 7;
  uint64 volume = 8;
  optional double vwap = 9;
}

// Order updates subscription request
message SubscribeOrderUpdatesRequest {
  optional string account_id = 1;
}

// Order update event
message OrderUpdateEvent {
  string order_id = 1;
  string symbol = 2;
  OrderStatus status = 3;
  double filled_quantity = 4;
  double remaining_quantity = 5;
  double last_fill_price = 6;
  uint64 last_fill_quantity = 7;
  int64 timestamp_unix_nanos = 8;
  string message = 9;
}


// Monitoring messages
message GetMetricsRequest {
  repeated string metric_names = 1;
  optional int64 start_time_unix_nanos = 2;
  optional int64 end_time_unix_nanos = 3;
}

message GetMetricsResponse {
  repeated Metric metrics = 1;
  int64 timestamp_unix_nanos = 2;
}

message Metric {
  string name = 1;
  double value = 2;
  string unit = 3;
  map<string, string> labels = 4;
  int64 timestamp_unix_nanos = 5;
}

message GetLatencyRequest {
  optional string service_name = 1;
  optional string operation = 2;
  optional int64 start_time_unix_nanos = 3;
  optional int64 end_time_unix_nanos = 4;
}

message GetLatencyResponse {
  double p50_micros = 1;
  double p95_micros = 2;
  double p99_micros = 3;
  double p999_micros = 4;
  double avg_micros = 5;
  double max_micros = 6;
  double min_micros = 7;
  uint64 sample_count = 8;
}

message GetThroughputRequest {
  optional string service_name = 1;
  optional string operation = 2;
  optional int64 start_time_unix_nanos = 3;
  optional int64 end_time_unix_nanos = 4;
}

message GetThroughputResponse {
  double requests_per_second = 1;
  double bytes_per_second = 2;
  uint64 total_requests = 3;
  uint64 total_bytes = 4;
  uint64 error_count = 5;
  double error_rate = 6;
}

message SubscribeMetricsRequest {
  repeated string metric_names = 1;
  uint32 interval_seconds = 2;
}

message MetricsEvent {
  repeated Metric metrics = 1;
  int64 timestamp_unix_nanos = 2;
}

// Configuration messages
message UpdateParametersRequest {
  map<string, string> parameters = 1;
  bool persist = 2;
}

message UpdateParametersResponse {
  bool success = 1;
  string message = 2;
  repeated string updated_keys = 3;
}

message GetConfigRequest {
  repeated string keys = 1; // Empty to get all config
}

message GetConfigResponse {
  map<string, string> config = 1;
  int64 version = 2;
  int64 last_updated_unix_nanos = 3;
}

message SubscribeConfigRequest {
  repeated string keys = 1; // Empty to watch all config changes
}

message ConfigEvent {
  string key = 1;
  string value = 2;
  string old_value = 3;
  int64 timestamp_unix_nanos = 4;
}

// Enums

// Order direction for trading operations
enum OrderSide {
  ORDER_SIDE_UNSPECIFIED = 0;           // Default/unknown side
  ORDER_SIDE_BUY = 1;                   // Buy order (long position)
  ORDER_SIDE_SELL = 2;                  // Sell order (short position)
}

// Order execution type
enum OrderType {
  ORDER_TYPE_UNSPECIFIED = 0;           // Default/unknown type
  ORDER_TYPE_MARKET = 1;                // Execute immediately at market price
  ORDER_TYPE_LIMIT = 2;                 // Execute only at specified price or better
  ORDER_TYPE_STOP = 3;                  // Market order triggered at stop price
  ORDER_TYPE_STOP_LIMIT = 4;            // Limit order triggered at stop price
}

// Current lifecycle status of orders
enum OrderStatus {
  ORDER_STATUS_UNSPECIFIED = 0;         // Default/unknown status
  ORDER_STATUS_NEW = 1;                 // Order created and submitted
  ORDER_STATUS_PARTIALLY_FILLED = 2;    // Order partially executed
  ORDER_STATUS_FILLED = 3;              // Order completely executed
  ORDER_STATUS_CANCELLED = 4;           // Order cancelled
  ORDER_STATUS_REJECTED = 5;            // Order rejected by exchange or system
  ORDER_STATUS_PENDING_CANCEL = 6;      // Cancellation request pending
}

enum MarketDataType {
  MARKET_DATA_TYPE_UNSPECIFIED = 0;
  MARKET_DATA_TYPE_TICKS = 1;
  MARKET_DATA_TYPE_QUOTES = 2;
  MARKET_DATA_TYPE_TRADES = 3;
  MARKET_DATA_TYPE_BARS = 4;
}


message GetSystemStatusRequest {
  repeated string service_names = 1; // Empty to get all services
}

message GetSystemStatusResponse {
  SystemStatus overall_status = 1;
  repeated ServiceStatus services = 2;
  int64 timestamp_unix_nanos = 3;
}

message ServiceStatus {
  string name = 1;
  SystemStatus status = 2;
  string message = 3;
  int64 last_check_unix_nanos = 4;
  map<string, string> details = 5;
}

message SubscribeSystemStatusRequest {
  repeated string service_names = 1;
}

message SystemStatusEvent {
  string service_name = 1;
  SystemStatus status = 2;
  SystemStatus previous_status = 3;
  string message = 4;
  int64 timestamp_unix_nanos = 5;
}

enum SystemStatus {
  SYSTEM_STATUS_UNKNOWN = 0;
  SYSTEM_STATUS_HEALTHY = 1;
  SYSTEM_STATUS_DEGRADED = 2;
  SYSTEM_STATUS_UNHEALTHY = 3;
  SYSTEM_STATUS_CRITICAL = 4;
}


// VaR calculation request
message GetVaRRequest {
  repeated string symbols = 1;
  double confidence_level = 2; // e.g., 0.95, 0.99
  uint32 lookback_days = 3;
  VaRMethodology methodology = 4;
}

// VaR calculation response
message GetVaRResponse {
  double portfolio_var = 1;
  repeated SymbolVaR symbol_vars = 2;
  int64 timestamp_unix_nanos = 3;
  string methodology_used = 4;
}

message SymbolVaR {
  string symbol = 1;
  double var_amount = 2;
  double contribution_percent = 3;
}

// Position risk analysis
message GetPositionRiskRequest {
  optional string symbol = 1; // Empty for all positions
}

message GetPositionRiskResponse {
  repeated PositionRisk positions = 1;
  double total_exposure = 2;
  double concentration_risk = 3;
  int64 timestamp_unix_nanos = 4;
}

message PositionRisk {
  string symbol = 1;
  double position_size = 2;
  double market_value = 3;
  double var_contribution = 4;
  double concentration_percent = 5;
  RiskLevel risk_level = 6;
}

// Order validation request
message ValidateOrderRequest {
  string symbol = 1;
  OrderSide side = 2;
  double quantity = 3;
  double price = 4;
  string account_id = 5;
}

message ValidateOrderResponse {
  bool approved = 1;
  string reason = 2;
  repeated RiskViolation violations = 3;
  double projected_exposure = 4;
  double margin_impact = 5;
}

message RiskViolation {
  ViolationType type = 1;
  string description = 2;
  double limit_value = 3;
  double current_value = 4;
  RiskSeverity severity = 5;
}

// Risk metrics request
message GetRiskMetricsRequest {
  optional string portfolio_id = 1;
  optional int64 start_time_unix_nanos = 2;
  optional int64 end_time_unix_nanos = 3;
}

message GetRiskMetricsResponse {
  double sharpe_ratio = 1;
  double max_drawdown = 2;
  double current_drawdown = 3;
  double volatility = 4;
  double beta = 5;
  double alpha = 6;
  double value_at_risk = 7;
  double expected_shortfall = 8;
  int64 timestamp_unix_nanos = 9;
}

// Risk alerts subscription
message SubscribeRiskAlertsRequest {
  repeated RiskSeverity min_severity = 1;
  repeated string symbols = 2; // Empty for all symbols
}

message RiskAlertEvent {
  string alert_id = 1;
  RiskSeverity severity = 2;
  string symbol = 3;
  string message = 4;
  double threshold_value = 5;
  double current_value = 6;
  int64 timestamp_unix_nanos = 7;
  bool requires_action = 8;
}

// Emergency stop
message EmergencyStopRequest {
  EmergencyStopType stop_type = 1;
  string reason = 2;
  repeated string symbols = 3; // Empty for all
  bool confirm = 4;
}

message EmergencyStopResponse {
  bool success = 1;
  string message = 2;
  uint32 orders_cancelled = 3;
  uint32 positions_closed = 4;
  int64 timestamp_unix_nanos = 5;
}

// Backtesting Service provides comprehensive strategy backtesting capabilities for the TLI.
// This service allows users to test trading strategies against historical data with detailed
// performance analytics, risk metrics, and trade-by-trade analysis.
service BacktestingService {
  // Backtest Execution Management
  // Start a new strategy backtest with historical data
  rpc StartBacktest(StartBacktestRequest) returns (StartBacktestResponse);
  
  // Get current status of a running backtest
  rpc GetBacktestStatus(GetBacktestStatusRequest) returns (GetBacktestStatusResponse);
  
  // Get comprehensive backtest results and analytics
  rpc GetBacktestResults(GetBacktestResultsRequest) returns (GetBacktestResultsResponse);
  
  // List historical backtest runs with filtering
  rpc ListBacktests(ListBacktestsRequest) returns (ListBacktestsResponse);
  
  // Subscribe to real-time backtest progress updates
  rpc SubscribeBacktestProgress(SubscribeBacktestProgressRequest) returns (stream BacktestProgressEvent);
  
  // Stop a running backtest and optionally save partial results
  rpc StopBacktest(StopBacktestRequest) returns (StopBacktestResponse);
}

// Start backtest request
message StartBacktestRequest {
  string strategy_name = 1;
  repeated string symbols = 2;
  int64 start_date_unix_nanos = 3;
  int64 end_date_unix_nanos = 4;
  double initial_capital = 5;
  map<string, string> parameters = 6;
  bool save_results = 7;
  string description = 8;
}

message StartBacktestResponse {
  bool success = 1;
  string backtest_id = 2;
  string message = 3;
  int64 estimated_duration_seconds = 4;
}

// Backtest status
message GetBacktestStatusRequest {
  string backtest_id = 1;
}

message GetBacktestStatusResponse {
  string backtest_id = 1;
  BacktestStatus status = 2;
  double progress_percentage = 3;
  string current_date = 4;
  uint64 trades_executed = 5;
  double current_pnl = 6;
  int64 started_at_unix_nanos = 7;
  optional int64 completed_at_unix_nanos = 8;
  optional string error_message = 9;
}

// Backtest results
message GetBacktestResultsRequest {
  string backtest_id = 1;
  bool include_trades = 2;
  bool include_metrics = 3;
}

message GetBacktestResultsResponse {
  string backtest_id = 1;
  BacktestMetrics metrics = 2;
  repeated Trade trades = 3;
  repeated EquityCurvePoint equity_curve = 4;
  repeated DrawdownPeriod drawdown_periods = 5;
}

message BacktestMetrics {
  double total_return = 1;
  double annualized_return = 2;
  double sharpe_ratio = 3;
  double sortino_ratio = 4;
  double max_drawdown = 5;
  double volatility = 6;
  double win_rate = 7;
  double profit_factor = 8;
  uint64 total_trades = 9;
  uint64 winning_trades = 10;
  uint64 losing_trades = 11;
  double avg_win = 12;
  double avg_loss = 13;
  double largest_win = 14;
  double largest_loss = 15;
  double calmar_ratio = 16;
  int64 backtest_duration_nanos = 17;
}

message Trade {
  string trade_id = 1;
  string symbol = 2;
  OrderSide side = 3;
  double quantity = 4;
  double entry_price = 5;
  double exit_price = 6;
  int64 entry_time_unix_nanos = 7;
  int64 exit_time_unix_nanos = 8;
  double pnl = 9;
  double return_percent = 10;
  string entry_signal = 11;
  string exit_signal = 12;
}

message EquityCurvePoint {
  int64 timestamp_unix_nanos = 1;
  double equity = 2;
  double drawdown = 3;
  double benchmark_equity = 4;
}

message DrawdownPeriod {
  int64 start_time_unix_nanos = 1;
  int64 end_time_unix_nanos = 2;
  double peak_value = 3;
  double trough_value = 4;
  double drawdown_percent = 5;
  uint32 duration_days = 6;
}

// List backtests
message ListBacktestsRequest {
  uint32 limit = 1;
  uint32 offset = 2;
  optional string strategy_name = 3;
  optional BacktestStatus status_filter = 4;
}

message ListBacktestsResponse {
  repeated BacktestSummary backtests = 1;
  uint32 total_count = 2;
}

message BacktestSummary {
  string backtest_id = 1;
  string strategy_name = 2;
  repeated string symbols = 3;
  BacktestStatus status = 4;
  double total_return = 5;
  double sharpe_ratio = 6;
  double max_drawdown = 7;
  int64 created_at_unix_nanos = 8;
  int64 start_date_unix_nanos = 9;
  int64 end_date_unix_nanos = 10;
  string description = 11;
}

// Backtest progress subscription
message SubscribeBacktestProgressRequest {
  string backtest_id = 1;
}

message BacktestProgressEvent {
  string backtest_id = 1;
  double progress_percentage = 2;
  string current_date = 3;
  uint64 trades_executed = 4;
  double current_pnl = 5;
  double current_equity = 6;
  BacktestStatus status = 7;
  int64 timestamp_unix_nanos = 8;
}

// Stop backtest
message StopBacktestRequest {
  string backtest_id = 1;
  bool save_partial_results = 2;
}

message StopBacktestResponse {
  bool success = 1;
  string message = 2;
  bool results_saved = 3;
}

// Additional enums for risk and backtesting
enum VaRMethodology {
  VAR_METHODOLOGY_UNSPECIFIED = 0;
  VAR_METHODOLOGY_HISTORICAL = 1;
  VAR_METHODOLOGY_MONTE_CARLO = 2;
  VAR_METHODOLOGY_PARAMETRIC = 3;
  VAR_METHODOLOGY_EXPECTED_SHORTFALL = 4;
}

enum RiskLevel {
  RISK_LEVEL_UNSPECIFIED = 0;
  RISK_LEVEL_LOW = 1;
  RISK_LEVEL_MEDIUM = 2;
  RISK_LEVEL_HIGH = 3;
  RISK_LEVEL_CRITICAL = 4;
}

enum ViolationType {
  VIOLATION_TYPE_UNSPECIFIED = 0;
  VIOLATION_TYPE_POSITION_LIMIT = 1;
  VIOLATION_TYPE_CONCENTRATION = 2;
  VIOLATION_TYPE_VAR_LIMIT = 3;
  VIOLATION_TYPE_MARGIN = 4;
  VIOLATION_TYPE_DRAWDOWN = 5;
}

enum RiskSeverity {
  RISK_SEVERITY_UNSPECIFIED = 0;
  RISK_SEVERITY_INFO = 1;
  RISK_SEVERITY_WARNING = 2;
  RISK_SEVERITY_CRITICAL = 3;
  RISK_SEVERITY_EMERGENCY = 4;
}

enum EmergencyStopType {
  EMERGENCY_STOP_TYPE_UNSPECIFIED = 0;
  EMERGENCY_STOP_TYPE_CANCEL_ORDERS = 1;
  EMERGENCY_STOP_TYPE_CLOSE_POSITIONS = 2;
  EMERGENCY_STOP_TYPE_FULL_SHUTDOWN = 3;
}

enum BacktestStatus {
  BACKTEST_STATUS_UNSPECIFIED = 0;
  BACKTEST_STATUS_QUEUED = 1;
  BACKTEST_STATUS_RUNNING = 2;
  BACKTEST_STATUS_COMPLETED = 3;
  BACKTEST_STATUS_FAILED = 4;
  BACKTEST_STATUS_CANCELLED = 5;
  BACKTEST_STATUS_PAUSED = 6;
}

// ML Trading Messages

// Submit ML-powered order request
message SubmitMLOrderRequest {
  string symbol = 1;                    // Trading symbol (e.g., "ES.FUT")
  string account_id = 2;                // Trading account identifier
  optional string model_filter = 3;     // Optional model filter: "DQN", "MAMBA2", "PPO", "TFT", or null for ensemble
}

// Submit ML-powered order response
message SubmitMLOrderResponse {
  string order_id = 1;                  // Order ID if executed
  string symbol = 2;                    // Trading symbol
  string model_used = 3;                // "Ensemble" or specific model name
  string predicted_action = 4;          // Action taken: BUY, SELL, HOLD
  double confidence = 5;                // Prediction confidence (0.0-1.0)
  int32 quantity = 6;                   // Order quantity
  bool executed = 7;                    // True if order was submitted
  string message = 8;                   // Status message
}

// Get ML predictions request
message GetMLPredictionsRequest {
  string symbol = 1;                    // Trading symbol to filter by
  optional string model_filter = 2;     // Optional model filter
  optional int32 limit = 3;             // Maximum predictions to return (default: 10)
}

// Get ML predictions response
message GetMLPredictionsResponse {
  repeated MLPrediction predictions = 1; // List of predictions with outcomes
}

// Single ML prediction with outcome
message MLPrediction {
  string timestamp = 1;                 // Prediction timestamp (ISO 8601)
  string model_id = 2;                  // Model identifier
  string symbol = 3;                    // Trading symbol
  string predicted_action = 4;          // Predicted action: BUY, SELL, HOLD
  double confidence = 5;                // Prediction confidence (0.0-1.0)
  optional double actual_return = 6;    // Actual return if outcome known
}

// Get ML performance request
message GetMLPerformanceRequest {
  optional string model_filter = 1;     // Optional model filter
}

// Get ML performance response
message GetMLPerformanceResponse {
  repeated ModelPerformance models = 1; // Performance metrics per model
  double ensemble_threshold = 2;        // Ensemble confidence threshold
  int32 active_models = 3;              // Number of active models
  int32 total_models = 4;               // Total number of models
}

// Performance metrics for a single model
message ModelPerformance {
  string model_id = 1;                  // Model identifier
  double accuracy = 2;                  // Accuracy rate (0.0-1.0)
  int64 total_predictions = 3;          // Total predictions made
  double sharpe_ratio = 4;              // Risk-adjusted return
  double avg_return = 5;                // Average return per prediction
  double max_drawdown = 6;              // Maximum drawdown
}

// Wave D: Regime Detection Messages

// Request to get current regime state
message GetRegimeStateRequest {
  string symbol = 1;                    // Trading symbol to query
}

// Response containing current regime state
message GetRegimeStateResponse {
  string symbol = 1;                    // Trading symbol
  string current_regime = 2;            // Current regime: TRENDING, RANGING, VOLATILE, CRISIS
  double confidence = 3;                // Regime confidence (0.0-1.0)
  double cusum_s_plus = 4;              // CUSUM S+ statistic
  double cusum_s_minus = 5;             // CUSUM S- statistic
  double adx = 6;                       // Average Directional Index
  double stability = 7;                 // Regime stability score (0.0-1.0)
  double entropy = 8;                   // Transition entropy (0.0-1.0)
  int64 updated_at_unix_nanos = 9;      // Last update timestamp
}

// Request to get regime transition history
message GetRegimeTransitionsRequest {
  string symbol = 1;                    // Trading symbol to query
  int32 limit = 2;                      // Maximum transitions to return (default: 100)
}

// Response containing regime transition history
message GetRegimeTransitionsResponse {
  repeated RegimeTransition transitions = 1; // List of regime transitions
}

// Single regime transition record
message RegimeTransition {
  string from_regime = 1;               // Previous regime
  string to_regime = 2;                 // New regime
  int32 duration_bars = 3;              // Duration in previous regime (bars)
  double transition_probability = 4;    // Transition probability from matrix
  int64 timestamp_unix_nanos = 5;       // Transition timestamp
}
