# IOrderManager Interface Design

## Overview

The IOrderManager interface is the core contract for the Order Management System (OMS) that defines all functionality required for order submission, management, algorithmic execution, and smart order routing.

## Interface Definition

```csharp
using NT8.Core.Common.Models;
using NT8.Core.Risk;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace NT8.Core.Orders
{
    /// <summary>
    /// Order management interface - handles order submission, routing, and execution
    /// </summary>
    public interface IOrderManager
    {
        #region Order Submission and Management
        
        /// <summary>
        /// Submit a new order for execution
        /// </summary>
        Task<OrderResult> SubmitOrderAsync(OrderRequest request, StrategyContext context);
        
        /// <summary>
        /// Cancel an existing order
        /// </summary>
        Task<bool> CancelOrderAsync(string orderId);
        
        /// <summary>
        /// Modify an existing order
        /// </summary>
        Task<OrderResult> ModifyOrderAsync(string orderId, OrderModification modification);
        
        /// <summary>
        /// Get order status
        /// </summary>
        Task<OrderStatus> GetOrderStatusAsync(string orderId);
        
        /// <summary>
        /// Get all orders for a symbol
        /// </summary>
        Task<List<OrderStatus>> GetOrdersBySymbolAsync(string symbol);
        
        /// <summary>
        /// Get all active orders
        /// </summary>
        Task<List<OrderStatus>> GetActiveOrdersAsync();
        
        #endregion
        
        #region Algorithmic Execution
        
        /// <summary>
        /// Execute a TWAP order
        /// </summary>
        Task<OrderResult> ExecuteTwapAsync(TwapParameters parameters, StrategyContext context);
        
        /// <summary>
        /// Execute a VWAP order
        /// </summary>
        Task<OrderResult> ExecuteVwapAsync(VwapParameters parameters, StrategyContext context);
        
        /// <summary>
        /// Execute an Iceberg order
        /// </summary>
        Task<OrderResult> ExecuteIcebergAsync(IcebergParameters parameters, StrategyContext context);
        
        #endregion
        
        #region Smart Order Routing
        
        /// <summary>
        /// Route order based on smart routing logic
        /// </summary>
        Task<RoutingResult> RouteOrderAsync(OrderRequest request, StrategyContext context);
        
        /// <summary>
        /// Get available execution venues
        /// </summary>
        List<ExecutionVenue> GetAvailableVenues();
        
        /// <summary>
        /// Get routing performance metrics
        /// </summary>
        RoutingMetrics GetRoutingMetrics();
        
        #endregion
        
        #region Risk Integration
        
        /// <summary>
        /// Validate order against risk parameters
        /// </summary>
        Task<RiskDecision> ValidateOrderAsync(OrderRequest request, StrategyContext context);
        
        #endregion
        
        #region Configuration and Management
        
        /// <summary>
        /// Update routing configuration
        /// </summary>
        void UpdateRoutingConfig(RoutingConfig config);
        
        /// <summary>
        /// Get current routing configuration
        /// </summary>
        RoutingConfig GetRoutingConfig();
        
        /// <summary>
        /// Update algorithm parameters
        /// </summary>
        void UpdateAlgorithmParameters(AlgorithmParameters parameters);
        
        /// <summary>
        /// Get current algorithm parameters
        /// </summary>
        AlgorithmParameters GetAlgorithmParameters();
        
        /// <summary>
        /// Reset OMS state
        /// </summary>
        void Reset();
        
        #endregion
        
        #region Monitoring and Metrics
        
        /// <summary>
        /// Get OMS performance metrics
        /// </summary>
        OmsMetrics GetMetrics();
        
        /// <summary>
        /// Check if OMS is healthy
        /// </summary>
        bool IsHealthy();
        
        #endregion
    }
}
```

## Supporting Data Models

### OrderRequest
```csharp
/// <summary>
/// Order request parameters
/// </summary>
public record OrderRequest(
    string Symbol,
    OrderSide Side,
    OrderType Type,
    int Quantity,
    decimal? LimitPrice,
    decimal? StopPrice,
    TimeInForce TimeInForce,
    string Algorithm, // TWAP, VWAP, Iceberg, or null for regular order
    Dictionary<string, object> AlgorithmParameters
);
```

### OrderResult
```csharp
/// <summary>
/// Order submission result
/// </summary>
public record OrderResult(
    bool Success,
    string OrderId,
    string Message,
    OrderStatus Status
);
```

### OrderStatus
```csharp
/// <summary>
/// Current order status
/// </summary>
public record OrderStatus(
    string OrderId,
    string Symbol,
    OrderSide Side,
    OrderType Type,
    int Quantity,
    int FilledQuantity,
    decimal? LimitPrice,
    decimal? StopPrice,
    OrderState State,
    DateTime CreatedTime,
    DateTime? FilledTime,
    List<OrderFill> Fills
);
```

### TwapParameters
```csharp
/// <summary>
/// TWAP algorithm parameters
/// </summary>
public record TwapParameters(
    string Symbol,
    OrderSide Side,
    int TotalQuantity,
    TimeSpan Duration,
    int IntervalSeconds,
    decimal? LimitPrice
);
```

### VwapParameters
```csharp
/// <summary>
/// VWAP algorithm parameters
/// </summary>
public record VwapParameters(
    string Symbol,
    OrderSide Side,
    int TotalQuantity,
    DateTime StartTime,
    DateTime EndTime,
    decimal? LimitPrice,
    double ParticipationRate // 0.0 to 1.0
);
```

### IcebergParameters
```csharp
/// <summary>
/// Iceberg algorithm parameters
/// </summary>
public record IcebergParameters(
    string Symbol,
    OrderSide Side,
    int TotalQuantity,
    int VisibleQuantity,
    decimal? LimitPrice
);
```

### RoutingResult
```csharp
/// <summary>
/// Order routing result
/// </summary>
public record RoutingResult(
    bool Success,
    string OrderId,
    ExecutionVenue SelectedVenue,
    string Message,
    Dictionary<string, object> RoutingDetails
);
```

### ExecutionVenue
```csharp
/// <summary>
/// Execution venue information
/// </summary>
public record ExecutionVenue(
    string Name,
    string Description,
    bool IsActive,
    double CostFactor, // Relative cost (1.0 = baseline)
    double SpeedFactor, // Relative speed (1.0 = baseline)
    double ReliabilityFactor // Reliability score (0.0 to 1.0)
);
```

### RoutingMetrics
```csharp
/// <summary>
/// Routing performance metrics
/// </summary>
public record RoutingMetrics(
    Dictionary<string, VenueMetrics> VenuePerformance,
    int TotalRoutedOrders,
    double AverageRoutingTimeMs,
    DateTime LastUpdated
);
```

### VenueMetrics
```csharp
/// <summary>
/// Metrics for a specific execution venue
/// </summary>
public record VenueMetrics(
    string VenueName,
    int OrdersRouted,
    double FillRate,
    double AverageSlippage,
    double AverageExecutionTimeMs,
    decimal TotalValueRouted
);
```

### RoutingConfig
```csharp
/// <summary>
/// Routing configuration parameters
/// </summary>
public record RoutingConfig(
    bool SmartRoutingEnabled,
    string DefaultVenue,
    Dictionary<string, double> VenuePreferences,
    double MaxSlippagePercent,
    TimeSpan MaxRoutingTime,
    bool RouteByCost,
    bool RouteBySpeed,
    bool RouteByReliability
);
```

### AlgorithmParameters
```csharp
/// <summary>
/// Algorithm configuration parameters
/// </summary>
public record AlgorithmParameters(
    TwapConfig TwapSettings,
    VwapConfig VwapSettings,
    IcebergConfig IcebergSettings
);
```

### OmsMetrics
```csharp
/// <summary>
/// OMS performance metrics
/// </summary>
public record OmsMetrics(
    int TotalOrders,
    int ActiveOrders,
    int FailedOrders,
    double FillRate,
    double AverageSlippage,
    double AverageExecutionTimeMs,
    decimal TotalValueTraded,
    DateTime LastUpdated
);
```

## Enumerations

### OrderType
```csharp
/// <summary>
/// Order type enumeration
/// </summary>
public enum OrderType
{
    Market,
    Limit,
    StopMarket,
    StopLimit
}
```

### OrderState
```csharp
/// <summary>
/// Order state enumeration
/// </summary>
public enum OrderState
{
    New,
    Submitted,
    Accepted,
    PartiallyFilled,
    Filled,
    Cancelled,
    Rejected,
    Expired
}
```

### TimeInForce
```csharp
/// <summary>
/// Time in force enumeration
/// </summary>
public enum TimeInForce
{
    Day,
    Gtc, // Good Till Cancelled
    Ioc, // Immediate Or Cancel
    Fok  // Fill Or Kill
}
```

## Integration Points

### Risk Management
The IOrderManager interface integrates with the existing IRiskManager to validate all orders before submission:

```csharp
// Before submitting any order, the OMS will call:
RiskDecision decision = await _riskManager.ValidateOrder(intent, context, config);
if (!decision.Allow)
{
    // Handle rejection
}
```

### Position Sizing
The OMS works with the IPositionSizer to determine appropriate order quantities:

```csharp
// Order quantities are determined by:
SizingResult sizing = _positionSizer.CalculateSize(intent, context, config);
int orderQuantity = sizing.Contracts;
```

## Implementation Requirements

1. **Thread Safety**: All methods must be thread-safe as multiple strategies may submit orders concurrently
2. **Error Handling**: Comprehensive error handling with meaningful error messages
3. **Logging**: Detailed logging of all order activities for audit and debugging
4. **Performance**: Optimized for low-latency order execution
5. **Configuration**: All parameters must be configurable without code changes
6. **Monitoring**: Comprehensive metrics collection for performance monitoring
7. **Testing**: All methods must be unit testable with mock dependencies

## Dependencies

1. NT8.Core.Risk.IRiskManager
2. NT8.Core.Sizing.IPositionSizer
3. NT8.Core.Common.Models.StrategyContext
4. Microsoft.Extensions.Logging.ILogger

## Extension Points

The interface is designed to be extensible:
- New algorithmic strategies can be added
- Additional execution venues can be integrated
- Custom routing logic can be implemented
- New order types can be supported
