syntax = "proto3";

package trading;

// Trading Service provides comprehensive real-time trading operations for high-frequency trading.
// This service handles order management, position tracking, market data streaming, and execution monitoring.
// All operations are designed for ultra-low latency with microsecond precision timing.
service TradingService {
  // Order Management Operations
  // Submit a new trading order with validation and risk checks
  rpc SubmitOrder(SubmitOrderRequest) returns (SubmitOrderResponse);
  
  // Cancel an existing order by order ID
  rpc CancelOrder(CancelOrderRequest) returns (CancelOrderResponse);
  
  // Get current status of a specific order
  rpc GetOrderStatus(GetOrderStatusRequest) returns (GetOrderStatusResponse);
  
  // Stream real-time order events for monitoring order lifecycle
  rpc StreamOrders(StreamOrdersRequest) returns (stream OrderEvent);

  // Position Management Operations
  // Get current positions for account and/or symbol
  rpc GetPositions(GetPositionsRequest) returns (GetPositionsResponse);
  
  // Stream real-time position updates as trades execute
  rpc StreamPositions(StreamPositionsRequest) returns (stream PositionEvent);
  
  // Get comprehensive portfolio summary with P&L and risk metrics
  rpc GetPortfolioSummary(GetPortfolioSummaryRequest) returns (GetPortfolioSummaryResponse);

  // Market Data Operations
  // Stream real-time market data (trades, quotes, order book)
  rpc StreamMarketData(StreamMarketDataRequest) returns (stream MarketDataEvent);
  
  // Get current order book snapshot for a symbol
  rpc GetOrderBook(GetOrderBookRequest) returns (GetOrderBookResponse);

  // Execution Operations
  // Stream real-time trade executions as they occur
  rpc StreamExecutions(StreamExecutionsRequest) returns (stream ExecutionEvent);
  
  // Get historical execution data with filtering options
  rpc GetExecutionHistory(GetExecutionHistoryRequest) returns (GetExecutionHistoryResponse);

  // ML-specific Trading Operations
  // Submit ML-generated trading order with ensemble predictions
  rpc SubmitMLOrder(MLOrderRequest) returns (MLOrderResponse);
  
  // Get ML prediction history with outcomes
  rpc GetMLPredictions(MLPredictionsRequest) returns (MLPredictionsResponse);
  
  // Get ML model performance metrics
  rpc GetMLPerformance(MLPerformanceRequest) returns (MLPerformanceResponse);

  // 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);

  // Server-streaming: polls GetPortfolioSummary at gateway level
  rpc StreamPortfolioSummary(StreamPortfolioSummaryRequest) returns (stream GetPortfolioSummaryResponse);

  // Server-streaming: polls GetOrderBook at gateway level
  rpc StreamOrderBook(StreamOrderBookRequest) returns (stream GetOrderBookResponse);
}

// Streaming request messages

message StreamPortfolioSummaryRequest {
  string account_id = 1;       // Account ID for portfolio summary
  uint32 interval_seconds = 2; // 0 = server default (3s)
}

message StreamOrderBookRequest {
  string symbol = 1;
  int32 depth = 2;
  uint32 interval_seconds = 3; // 0 = server default (1s)
}

// Order Management Messages

// Request to submit a new trading order
message SubmitOrderRequest {
  string symbol = 1;                    // Trading symbol (e.g., "AAPL", "BTC-USD")
  OrderSide side = 2;                   // Buy or sell direction
  double quantity = 3;                  // Number of shares/units to trade
  OrderType order_type = 4;             // Market, limit, stop, or stop-limit
  optional double price = 5;            // Limit price (required for limit orders)
  optional double stop_price = 6;       // Stop price (required for stop orders)
  string account_id = 7;                // Trading account identifier
  map<string, string> metadata = 8;     // Additional order metadata (strategy, tags, etc.)
}

// Response after submitting an order
message SubmitOrderResponse {
  string order_id = 1;                  // Unique order identifier assigned by system
  OrderStatus status = 2;               // Current order status (pending, submitted, etc.)
  string message = 3;                   // Status message or error description
  int64 timestamp = 4;                  // Order submission timestamp (nanoseconds)
}

// Request to cancel an existing order
message CancelOrderRequest {
  string order_id = 1;                  // Order ID to cancel
  string account_id = 2;                // Account ID for verification
}

// Response after attempting to cancel an order
message CancelOrderResponse {
  bool success = 1;                     // True if cancellation was successful
  string message = 2;                   // Success confirmation or error message
  int64 timestamp = 3;                  // Cancellation timestamp (nanoseconds)
}

// Request to get current status of an order
message GetOrderStatusRequest {
  string order_id = 1;                  // Order ID to query
}

// Response containing order status information
message GetOrderStatusResponse {
  Order order = 1;                      // Complete order details with current status
}

// Request to stream real-time order events
message StreamOrdersRequest {
  optional string account_id = 1;       // Filter by account (all accounts if not specified)
  optional string symbol = 2;           // Filter by symbol (all symbols if not specified)
}

// Position Management Messages

// Request to get current positions
message GetPositionsRequest {
  optional string account_id = 1;       // Filter by account (all accounts if not specified)
  optional string symbol = 2;           // Filter by symbol (all symbols if not specified)
}

// Response containing position information
message GetPositionsResponse {
  repeated Position positions = 1;      // List of current positions
}

// Request to stream real-time position updates
message StreamPositionsRequest {
  optional string account_id = 1;       // Filter by account (all accounts if not specified)
}

// Request for portfolio summary
message GetPortfolioSummaryRequest {
  string account_id = 1;                // Account ID for portfolio summary
}

// Response containing comprehensive portfolio information
message GetPortfolioSummaryResponse {
  double total_value = 1;               // Total portfolio value in USD
  double unrealized_pnl = 2;            // Unrealized profit/loss
  double realized_pnl = 3;              // Realized profit/loss for the day
  double day_pnl = 4;                   // Total P&L for the current trading day
  double buying_power = 5;              // Available buying power
  double margin_used = 6;               // Amount of margin currently used
  repeated Position positions = 7;      // Detailed position information
}

// Market Data Messages

// Request to stream real-time market data
message StreamMarketDataRequest {
  repeated string symbols = 1;          // List of symbols to subscribe to
  repeated MarketDataType data_types = 2; // Types of data to stream (trades, quotes, order book)
}

// Request for order book snapshot
message GetOrderBookRequest {
  string symbol = 1;                    // Symbol to get order book for
  optional int32 depth = 2;             // Number of price levels (default: full book)
}

// Response containing order book data
message GetOrderBookResponse {
  OrderBook order_book = 1;             // Current order book snapshot
}

// Execution Messages

// Request to stream real-time executions
message StreamExecutionsRequest {
  optional string account_id = 1;       // Filter by account (all accounts if not specified)
  optional string symbol = 2;           // Filter by symbol (all symbols if not specified)
}

// Request for historical execution data
message GetExecutionHistoryRequest {
  optional string account_id = 1;       // Filter by account (all accounts if not specified)
  optional string symbol = 2;           // Filter by symbol (all symbols if not specified)
  optional int64 start_time = 3;        // Start time for query (nanoseconds)
  optional int64 end_time = 4;          // End time for query (nanoseconds)
  optional int32 limit = 5;             // Maximum number of executions to return
}

// Response containing execution history
message GetExecutionHistoryResponse {
  repeated Execution executions = 1;    // List of historical executions
}

// ML Trading Messages

// Request to submit ML-generated order
message MLOrderRequest {
  string symbol = 1;                    // Trading symbol (e.g., "ES.FUT")
  string account_id = 2;                // Trading account identifier
  bool use_ensemble = 3;                // Use ensemble voting or specific model
  optional string model_name = 4;       // Specific model name if not using ensemble
  repeated double features = 5;         // Feature vector for ML prediction (26 features: OHLCV + technicals)
}

// Response after submitting ML order
message MLOrderResponse {
  string order_id = 1;                  // Order ID if executed
  string prediction_id = 2;             // Prediction ID from ensemble_predictions table
  string action = 3;                    // Action taken: BUY, SELL, HOLD
  double confidence = 4;                // Prediction confidence (0.0-1.0)
  string message = 5;                   // Status message
  bool executed = 6;                    // True if order was executed
}

// Request to get ML prediction history
message MLPredictionsRequest {
  string symbol = 1;                    // Trading symbol to filter by
  optional string model_name = 2;       // Filter by specific model
  int32 limit = 3;                      // Maximum predictions to return (default: 100)
  optional int64 start_time = 4;        // Start time filter (nanoseconds)
  optional int64 end_time = 5;          // End time filter (nanoseconds)
}

// Response containing ML prediction history
message MLPredictionsResponse {
  repeated MLPrediction predictions = 1; // List of predictions with outcomes
}

// Single ML prediction with outcome
message MLPrediction {
  string id = 1;                        // Prediction ID (UUID)
  string symbol = 2;                    // Trading symbol
  string ensemble_action = 3;           // Predicted action: BUY, SELL, HOLD
  double ensemble_signal = 4;           // Signal strength (-1.0 to 1.0)
  double ensemble_confidence = 5;       // Confidence level (0.0-1.0)
  int64 timestamp = 6;                  // Prediction timestamp (nanoseconds)
  optional string order_id = 7;         // Order ID if executed
  optional double actual_pnl = 8;       // Actual P&L if order filled
  repeated ModelPrediction model_predictions = 9; // Individual model predictions
}

// Individual model prediction within ensemble
message ModelPrediction {
  string model_name = 1;                // Model name (DQN, MAMBA2, PPO, TFT)
  double signal = 2;                    // Model signal strength
  double confidence = 3;                // Model confidence
}

// Request to get ML model performance metrics
message MLPerformanceRequest {
  optional string model_name = 1;       // Filter by specific model (or all if not specified)
  optional int64 start_time = 2;        // Start time for metrics (nanoseconds)
  optional int64 end_time = 3;          // End time for metrics (nanoseconds)
}

// Response containing ML model performance
message MLPerformanceResponse {
  repeated ModelPerformance models = 1; // Performance metrics per model
}

// Performance metrics for a single model
message ModelPerformance {
  string model_name = 1;                // Model name
  int64 total_predictions = 2;          // Total predictions made
  int64 correct_predictions = 3;        // Correct predictions (profitable)
  double accuracy = 4;                  // Accuracy rate (0.0-1.0)
  double sharpe_ratio = 5;              // Risk-adjusted return
  double avg_pnl = 6;                   // Average P&L per prediction
}

// 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 = 9;                 // Last update timestamp (nanoseconds)
}

// 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 = 5;                  // Transition timestamp (nanoseconds)
}

// Core Data Types

// Complete order information with all lifecycle details
message Order {
  string order_id = 1;                  // Unique order identifier
  string symbol = 2;                    // Trading symbol (e.g., "AAPL", "BTC-USD")
  OrderSide side = 3;                   // Buy or sell direction
  double quantity = 4;                  // Total quantity ordered
  double filled_quantity = 5;           // Quantity already filled
  OrderType order_type = 6;             // Market, limit, stop, or stop-limit
  optional double price = 7;            // Limit price (for limit orders)
  optional double stop_price = 8;       // Stop price (for stop orders)
  OrderStatus status = 9;               // Current order status
  int64 created_at = 10;                // Order creation timestamp (nanoseconds)
  optional int64 updated_at = 11;       // Last update timestamp (nanoseconds)
  string account_id = 12;               // Associated trading account
  map<string, string> metadata = 13;    // Additional order metadata
}

// Current position information for a symbol
message Position {
  string symbol = 1;                    // Trading symbol
  double quantity = 2;                  // Current position size (positive for long, negative for short)
  double average_price = 3;             // Average cost basis per share
  double market_value = 4;              // Current market value of position
  double unrealized_pnl = 5;            // Unrealized profit/loss
  double realized_pnl = 6;              // Realized profit/loss for the day
  string account_id = 7;                // Associated trading account
  int64 updated_at = 8;                 // Last update timestamp (nanoseconds)
}

// Trade execution details
message Execution {
  string execution_id = 1;              // Unique execution identifier
  string order_id = 2;                  // Associated order ID
  string symbol = 3;                    // Trading symbol
  OrderSide side = 4;                   // Buy or sell direction
  double quantity = 5;                  // Quantity executed
  double price = 6;                     // Execution price
  int64 timestamp = 7;                  // Execution timestamp (nanoseconds)
  string account_id = 8;                // Associated trading account
  map<string, string> metadata = 9;     // Additional execution metadata
}

// Order book snapshot for a symbol
message OrderBook {
  string symbol = 1;                    // Trading symbol
  repeated OrderBookLevel bids = 2;     // Bid levels (buyers) sorted by price descending
  repeated OrderBookLevel asks = 3;     // Ask levels (sellers) sorted by price ascending
  int64 timestamp = 4;                  // Order book timestamp (nanoseconds)
}

// Single price level in the order book
message OrderBookLevel {
  double price = 1;                     // Price level
  double quantity = 2;                  // Total quantity at this price level
  int32 order_count = 3;                // Number of orders at this price level
}

// Event Messages

// Real-time order event notification
message OrderEvent {
  string order_id = 1;                  // Order identifier
  Order order = 2;                      // Complete order details
  OrderEventType event_type = 3;        // Type of event (created, updated, filled, etc.)
  int64 timestamp = 4;                  // Event timestamp (nanoseconds)
  string message = 5;                   // Event message or additional details
}

// Real-time position change notification
message PositionEvent {
  string symbol = 1;                    // Trading symbol
  Position position = 2;                // Updated position details
  PositionEventType event_type = 3;     // Type of event (opened, updated, closed)
  int64 timestamp = 4;                  // Event timestamp (nanoseconds)
  double quantity = 5;                  // Position quantity (quick access)
  double average_price = 6;             // Average entry price (quick access)
  double unrealized_pnl = 7;            // Unrealized P&L (quick access)
}

// Real-time execution notification
message ExecutionEvent {
  string execution_id = 1;              // Execution identifier
  Execution execution = 2;              // Execution details
  int64 timestamp = 3;                  // Event timestamp (nanoseconds)
  string order_id = 4;                  // Associated order ID (quick access)
  string symbol = 5;                    // Trading symbol (quick access)
  double quantity = 6;                  // Executed quantity (quick access)
  double price = 7;                     // Execution price (quick access)
}

// Real-time market data update
message MarketDataEvent {
  string symbol = 1;                    // Trading symbol
  MarketDataType data_type = 2;         // Type of market data
  oneof data {
    Trade trade = 3;                    // Trade data (when data_type = TRADE)
    Quote quote = 4;                    // Quote data (when data_type = QUOTE)
    OrderBook order_book = 5;           // Order book data (when data_type = ORDER_BOOK)
  }
  int64 timestamp = 6;                  // Market data timestamp (nanoseconds)
}

// Market trade information
message Trade {
  double price = 1;                     // Trade price
  double volume = 2;                    // Trade volume
  int64 timestamp = 3;                  // Trade timestamp (nanoseconds)
}

// Market quote (bid/ask) information
message Quote {
  double bid_price = 1;                 // Best bid price
  double bid_size = 2;                  // Size at best bid
  double ask_price = 3;                 // Best ask price
  double ask_size = 4;                  // Size at best ask
  int64 timestamp = 5;                  // Quote timestamp (nanoseconds)
}

// Enums

// Order direction (buy or sell)
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 type determining execution behavior
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 status of an order in its lifecycle
enum OrderStatus {
  ORDER_STATUS_UNSPECIFIED = 0;        // Default/unknown status
  ORDER_STATUS_PENDING = 1;            // Order created but not yet submitted
  ORDER_STATUS_SUBMITTED = 2;          // Order submitted to exchange
  ORDER_STATUS_PARTIALLY_FILLED = 3;   // Order partially executed
  ORDER_STATUS_FILLED = 4;             // Order completely executed
  ORDER_STATUS_CANCELLED = 5;          // Order cancelled by user or system
  ORDER_STATUS_REJECTED = 6;           // Order rejected by exchange or risk system
}

// Type of order event notification
enum OrderEventType {
  ORDER_EVENT_TYPE_UNSPECIFIED = 0;    // Default/unknown event
  ORDER_EVENT_TYPE_CREATED = 1;        // Order was created
  ORDER_EVENT_TYPE_UPDATED = 2;        // Order details were updated
  ORDER_EVENT_TYPE_FILLED = 3;         // Order was executed (full or partial)
  ORDER_EVENT_TYPE_CANCELLED = 4;      // Order was cancelled
  ORDER_EVENT_TYPE_PARTIALLY_FILLED = 5; // Order was partially filled
  ORDER_EVENT_TYPE_REJECTED = 6;       // Order was rejected
}

// Type of position change event
enum PositionEventType {
  POSITION_EVENT_TYPE_UNSPECIFIED = 0; // Default/unknown event
  POSITION_EVENT_TYPE_OPENED = 1;      // New position was opened
  POSITION_EVENT_TYPE_UPDATED = 2;     // Existing position was modified
  POSITION_EVENT_TYPE_CLOSED = 3;      // Position was closed
}

// Type of market data being streamed
enum MarketDataType {
  MARKET_DATA_TYPE_UNSPECIFIED = 0;    // Default/unknown type
  MARKET_DATA_TYPE_TRADE = 1;          // Trade/transaction data
  MARKET_DATA_TYPE_QUOTE = 2;          // Best bid/ask quotes
  MARKET_DATA_TYPE_ORDER_BOOK = 3;     // Full order book depth
}
