openapi: 3.0.3 info: title: Foxhunt HFT System REST API description: | Comprehensive REST API for the Foxhunt High-Frequency Trading System. **PRODUCTION WARNING**: This API handles real financial transactions where mistakes cost real money. All endpoints implement comprehensive validation, risk management, and audit trails. ## Features - Sub-millisecond response times for critical trading operations - JWT authentication with Role-Based Access Control (RBAC) - Circuit breakers and rate limiting for system stability - Comprehensive error handling with financial context - Real-time market data streaming capabilities - AI-powered trading signals and sentiment analysis ## Authentication All protected endpoints require JWT Bearer tokens: ``` Authorization: Bearer ``` ## Rate Limits - Trading endpoints: 1,000 requests/minute per account - Market data: 10,000 requests/minute per API key - Analytics: 100 requests/minute per user ## Error Handling All errors follow RFC 7807 Problem Details format with financial context. version: 1.0.0 contact: name: Foxhunt API Support email: api-support@foxhunt-hft.com url: https://docs.foxhunt-hft.com license: name: Proprietary url: https://foxhunt-hft.com/license servers: - url: https://api.foxhunt-hft.com/v1 description: Production API - url: https://api-staging.foxhunt-hft.com/v1 description: Staging API - url: http://localhost:8080/v1 description: Local Development security: - BearerAuth: [] tags: - name: Health description: Service health and status monitoring - name: Trading description: Order management and trade execution - name: Market Data description: Real-time market data and order books - name: AI Intelligence description: AI-powered analysis and signal generation - name: Broker description: External broker connectivity and operations - name: Analytics description: Performance analytics and reporting - name: Admin description: Administrative operations (Admin role required) paths: # ============================================================================= # Health and Status Endpoints # ============================================================================= /health: get: tags: [Health] summary: Service health check description: | Comprehensive health status for all system components. Used by load balancers and monitoring systems. security: [] responses: '200': description: Service is healthy content: application/json: schema: $ref: '#/components/schemas/HealthResponse' example: status: healthy version: "1.0.0" uptime_seconds: 3600 components: trading_engine: { status: healthy, error_count: 0 } market_data: { status: healthy, error_count: 2 } persistence: { status: healthy, error_count: 1 } /health/public: get: tags: [Health] summary: Public health check (no authentication) description: Basic health status without sensitive information security: [] responses: '200': description: Public health status content: application/json: schema: type: object properties: status: type: string enum: [healthy, degraded, unhealthy] service: type: string timestamp: type: string format: date-time # ============================================================================= # Trading Engine Endpoints # ============================================================================= /trading/orders: post: tags: [Trading] summary: Place a new order description: | Submit a new trading order with comprehensive risk management. **CRITICAL**: This endpoint handles real money transactions. All orders are subject to: - Real-time risk validation - Position limit checks - Regulatory compliance verification - Audit trail generation security: - BearerAuth: [] requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/OrderRequest' example: client_order_id: "client-order-123" symbol: "AAPL" side: "BUY" order_type: "LIMIT" quantity: 100 price: 150.50 time_in_force: "GTC" account_id: "account-456" responses: '201': description: Order placed successfully content: application/json: schema: $ref: '#/components/schemas/OrderResponse' '400': $ref: '#/components/responses/BadRequest' '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '422': $ref: '#/components/responses/RiskViolation' '429': $ref: '#/components/responses/RateLimit' '500': $ref: '#/components/responses/InternalError' /trading/orders/{orderId}: get: tags: [Trading] summary: Get order details parameters: - name: orderId in: path required: true schema: type: string description: System-generated order ID responses: '200': description: Order details content: application/json: schema: $ref: '#/components/schemas/OrderDetail' '404': $ref: '#/components/responses/NotFound' delete: tags: [Trading] summary: Cancel an order description: | Cancel an existing order. Once cancelled, an order cannot be reactivated. **Performance Target**: < 500ns latency parameters: - name: orderId in: path required: true schema: type: string requestBody: content: application/json: schema: type: object properties: reason: type: string description: Cancellation reason for audit trail example: "User requested" responses: '200': description: Order cancelled successfully content: application/json: schema: $ref: '#/components/schemas/CancelResponse' '404': $ref: '#/components/responses/NotFound' '409': description: Order cannot be cancelled (already filled/cancelled) /trading/orderbook/{symbol}: get: tags: [Market Data] summary: Get order book snapshot description: | Retrieve current order book for a trading symbol. Data is real-time with nanosecond timestamp precision. parameters: - name: symbol in: path required: true schema: type: string description: Trading symbol (e.g., AAPL, EURUSD) example: "AAPL" - name: depth in: query schema: type: integer minimum: 1 maximum: 100 default: 10 description: Number of price levels to return responses: '200': description: Order book snapshot content: application/json: schema: $ref: '#/components/schemas/OrderBook' /trading/positions: get: tags: [Trading] summary: Get current positions description: | Retrieve all current positions for the authenticated account. Includes real-time P&L calculations and risk metrics. parameters: - name: symbol in: query schema: type: string description: Filter by specific symbol - name: account_id in: query schema: type: string description: Filter by account (Admin only) responses: '200': description: Current positions content: application/json: schema: type: object properties: positions: type: array items: $ref: '#/components/schemas/Position' total_unrealized_pnl: type: number format: double description: Total unrealized P&L across all positions total_realized_pnl: type: number format: double description: Total realized P&L for the day timestamp: type: string format: date-time # ============================================================================= # AI Intelligence Endpoints # ============================================================================= /ai/llm/generate: post: tags: [AI Intelligence] summary: Generate text using Financial LLM description: | Generate financial analysis and insights using AI language models. **Performance**: < 2 seconds response time **Context**: Specialized for financial markets and trading requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/GenerateRequest' example: prompt: "Analyze AAPL's Q4 earnings and provide investment outlook" parameters: max_tokens: 500 temperature: 0.7 responses: '200': description: Generated text content: application/json: schema: $ref: '#/components/schemas/GenerateResponse' /ai/sentiment: get: tags: [AI Intelligence] summary: Get market sentiment analysis description: | Retrieve aggregated market sentiment from multiple sources including news articles, social media, and analyst reports. parameters: - name: symbol in: query schema: type: string description: Filter sentiment for specific symbol - name: include_market in: query schema: type: boolean default: false description: Include overall market sentiment responses: '200': description: Sentiment analysis data content: application/json: schema: $ref: '#/components/schemas/SentimentResponse' /ai/sentiment/symbol/{symbol}: get: tags: [AI Intelligence] summary: Get symbol-specific sentiment parameters: - name: symbol in: path required: true schema: type: string example: "AAPL" responses: '200': description: Symbol sentiment content: application/json: schema: $ref: '#/components/schemas/SymbolSentiment' '404': $ref: '#/components/responses/NotFound' /ai/signals: get: tags: [AI Intelligence] summary: Get active trading signals description: | Retrieve AI-generated trading signals with confidence scores. Signals are updated in real-time based on market conditions. parameters: - name: symbol in: query schema: type: string description: Filter by trading symbol - name: min_confidence in: query schema: type: number format: float minimum: 0.0 maximum: 1.0 description: Minimum confidence threshold - name: signal_type in: query schema: type: string enum: [buy, sell, hold] description: Filter by signal type responses: '200': description: Active trading signals content: application/json: schema: type: array items: $ref: '#/components/schemas/TradingSignal' post: tags: [AI Intelligence] summary: Generate trading signal description: Generate trading signal based on custom market features requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/SignalRequest' responses: '200': description: Generated signal content: application/json: schema: $ref: '#/components/schemas/TradingSignal' /ai/signals/{signalId}: get: tags: [AI Intelligence] summary: Get specific signal details parameters: - name: signalId in: path required: true schema: type: string responses: '200': description: Signal details content: application/json: schema: $ref: '#/components/schemas/TradingSignal' '404': $ref: '#/components/responses/NotFound' # ============================================================================= # Admin Endpoints # ============================================================================= /admin/emergency-stop: post: tags: [Admin] summary: Emergency system stop description: | **CRITICAL OPERATION**: Immediately halt all trading activities. This endpoint: - Cancels all pending orders - Stops all trading strategies - Enables emergency mode - Requires Admin role **Use only in emergency situations** security: - BearerAuth: [] responses: '200': description: Emergency stop initiated content: application/json: schema: type: object properties: status: type: string example: "emergency_stop_initiated" initiated_by: type: string description: User ID who initiated the stop timestamp: type: string format: date-time orders_cancelled: type: integer description: Number of orders cancelled '403': $ref: '#/components/responses/Forbidden' /admin/metrics: get: tags: [Admin] summary: Get system metrics description: Prometheus-compatible metrics for monitoring security: - BearerAuth: [] responses: '200': description: System metrics content: text/plain: schema: type: string description: Prometheus metrics format # ============================================================================= # Broker Connector Endpoints # ============================================================================= /broker/accounts: get: tags: [Broker] summary: Get broker account information description: Retrieve account details from external broker responses: '200': description: Account information content: application/json: schema: type: array items: $ref: '#/components/schemas/BrokerAccount' /broker/positions: get: tags: [Broker] summary: Get broker positions description: Retrieve current positions from external broker responses: '200': description: Broker positions content: application/json: schema: type: array items: $ref: '#/components/schemas/BrokerPosition' components: securitySchemes: BearerAuth: type: http scheme: bearer bearerFormat: JWT description: | JWT Bearer token authentication. Include in Authorization header: ``` Authorization: Bearer ``` schemas: # ============================================================================= # Core Financial Types # ============================================================================= Money: type: object properties: amount: type: number format: double description: Monetary amount with high precision currency: type: string description: Currency code (USD, EUR, etc.) example: "USD" required: [amount, currency] Symbol: type: object properties: ticker: type: string description: Trading symbol example: "AAPL" exchange: type: string description: Exchange identifier example: "NASDAQ" asset_class: type: string description: Asset class enum: [EQUITY, FOREX, CRYPTO, COMMODITY, BOND] example: "EQUITY" required: [ticker, exchange, asset_class] # ============================================================================= # Trading Types # ============================================================================= OrderRequest: type: object properties: client_order_id: type: string description: Client-provided unique order ID example: "client-order-123" symbol: type: string description: Trading symbol example: "AAPL" side: type: string enum: [BUY, SELL] description: Order side order_type: type: string enum: [MARKET, LIMIT, STOP, STOP_LIMIT, ICEBERG] description: Order type quantity: type: number minimum: 0 description: Order quantity example: 100 price: type: number minimum: 0 description: Limit price (required for LIMIT orders) example: 150.50 time_in_force: type: string enum: [GTC, IOC, FOK, GTD] description: Time in force default: GTC account_id: type: string description: Trading account ID example: "account-456" iceberg_visible_qty: type: number minimum: 0 description: Visible quantity for iceberg orders expire_time: type: string format: date-time description: Expiry time for GTD orders required: [client_order_id, symbol, side, order_type, quantity, account_id] OrderResponse: type: object properties: order_id: type: string description: System-generated order ID client_order_id: type: string description: Client order ID status: type: string enum: [PENDING, PARTIALLY_FILLED, FILLED, CANCELLED, REJECTED] message: type: string description: Status message or error details timestamp: type: string format: date-time fills: type: array items: $ref: '#/components/schemas/Fill' risk_result: $ref: '#/components/schemas/RiskCheckResult' required: [order_id, client_order_id, status, timestamp] OrderDetail: allOf: - $ref: '#/components/schemas/OrderResponse' - type: object properties: symbol: type: string side: type: string enum: [BUY, SELL] order_type: type: string enum: [MARKET, LIMIT, STOP, STOP_LIMIT, ICEBERG] quantity: type: number price: type: number filled_quantity: type: number remaining_quantity: type: number average_price: type: number time_in_force: type: string account_id: type: string CancelResponse: type: object properties: order_id: type: string status: type: string enum: [CANCELLED] message: type: string timestamp: type: string format: date-time required: [order_id, status, timestamp] Fill: type: object properties: fill_id: type: string description: Unique fill identifier order_id: type: string description: Associated order ID symbol: type: string side: type: string enum: [BUY, SELL] quantity: type: number description: Filled quantity price: type: number description: Fill price timestamp: type: string format: date-time liquidity_flag: type: string enum: [ADDED, REMOVED, ROUTED] description: Liquidity provision flag required: [fill_id, order_id, symbol, side, quantity, price, timestamp] Position: type: object properties: symbol: type: string account_id: type: string quantity: type: number description: Position size (positive for long, negative for short) average_price: type: number description: Average entry price unrealized_pnl: type: number description: Current unrealized P&L realized_pnl: type: number description: Realized P&L for the day last_updated: type: string format: date-time required: [symbol, account_id, quantity, average_price, unrealized_pnl, realized_pnl] OrderBook: type: object properties: symbol: type: string bids: type: array items: $ref: '#/components/schemas/PriceLevel' description: Buy-side order book (highest price first) asks: type: array items: $ref: '#/components/schemas/PriceLevel' description: Sell-side order book (lowest price first) timestamp: type: string format: date-time sequence: type: integer format: int64 description: Sequence number for ordering updates required: [symbol, bids, asks, timestamp, sequence] PriceLevel: type: object properties: price: type: number description: Price level quantity: type: number description: Total quantity at this price level order_count: type: integer description: Number of orders at this price level required: [price, quantity, order_count] RiskCheckResult: type: object properties: passed: type: boolean description: Whether risk checks passed violations: type: array items: type: string description: List of risk violations risk_exposure: type: number description: Current risk exposure available_buying_power: type: number description: Available buying power required: [passed] # ============================================================================= # AI Intelligence Types # ============================================================================= GenerateRequest: type: object properties: prompt: type: string description: Text prompt for the LLM example: "Analyze AAPL's Q4 earnings and provide investment outlook" parameters: type: object properties: max_tokens: type: integer minimum: 1 maximum: 4000 default: 1000 temperature: type: number minimum: 0.0 maximum: 2.0 default: 0.7 top_p: type: number minimum: 0.0 maximum: 1.0 default: 1.0 required: [prompt] GenerateResponse: type: object properties: data: type: object properties: generated_text: type: string description: AI-generated text confidence: type: number minimum: 0.0 maximum: 1.0 description: Confidence score processing_time_ms: type: integer description: Processing time in milliseconds timestamp: type: string format: date-time request_id: type: string description: Unique request identifier required: [data, timestamp, request_id] SentimentResponse: type: object properties: symbol_sentiment: $ref: '#/components/schemas/SymbolSentiment' market_sentiment: $ref: '#/components/schemas/MarketSentiment' aggregated_sentiment: type: object properties: overall_score: type: number minimum: -1.0 maximum: 1.0 confidence: type: number minimum: 0.0 maximum: 1.0 SymbolSentiment: type: object properties: symbol: type: string sentiment_score: type: number minimum: -1.0 maximum: 1.0 description: Sentiment score (-1 very negative, +1 very positive) confidence: type: number minimum: 0.0 maximum: 1.0 source_count: type: integer description: Number of sources analyzed last_updated: type: string format: date-time required: [symbol, sentiment_score, confidence, source_count] MarketSentiment: type: object properties: overall_sentiment: type: number minimum: -1.0 maximum: 1.0 fear_greed_index: type: number minimum: 0.0 maximum: 100.0 volatility_index: type: number market_regime: type: string enum: [BULL, BEAR, SIDEWAYS, VOLATILE] last_updated: type: string format: date-time required: [overall_sentiment, last_updated] TradingSignal: type: object properties: signal_id: type: string symbol: type: string signal_type: type: string enum: [BUY, SELL, HOLD, CLOSE] strength: type: string enum: [WEAK, MODERATE, STRONG, VERY_STRONG] confidence: type: number minimum: 0.0 maximum: 1.0 target_price: type: number stop_loss: type: number timestamp: type: string format: date-time strategy_id: type: string metadata: type: object additionalProperties: true required: [signal_id, symbol, signal_type, strength, confidence, timestamp] SignalRequest: type: object properties: symbol: type: string example: "AAPL" price_change: type: number minimum: -1.0 maximum: 1.0 description: Price change percentage volume_ratio: type: number minimum: 0.0 description: Volume ratio vs average volatility: type: number minimum: 0.0 maximum: 1.0 rsi: type: number minimum: 0.0 maximum: 100.0 macd: type: number required: [symbol] # ============================================================================= # Broker Types # ============================================================================= BrokerAccount: type: object properties: account_id: type: string account_name: type: string balance: type: number available_balance: type: number currency: type: string leverage: type: number margin_used: type: number margin_available: type: number required: [account_id, account_name, balance, available_balance, currency] BrokerPosition: type: object properties: position_id: type: string symbol: type: string side: type: string enum: [LONG, SHORT] quantity: type: number entry_price: type: number current_price: type: number unrealized_pnl: type: number swap: type: number commission: type: number required: [position_id, symbol, side, quantity, entry_price, current_price, unrealized_pnl] # ============================================================================= # System Types # ============================================================================= HealthResponse: type: object properties: status: type: string enum: [healthy, degraded, unhealthy] version: type: string uptime_seconds: type: integer components: type: object additionalProperties: type: object properties: status: type: string enum: [healthy, degraded, unhealthy] error_count: type: integer last_activity: type: string format: date-time required: [status, version, uptime_seconds] ErrorResponse: type: object properties: error: type: string description: Machine-readable error code message: type: string description: Human-readable error message request_id: type: string description: Request ID for tracing timestamp: type: string format: date-time details: type: object description: Additional error context required: [error, message, request_id, timestamp] responses: BadRequest: description: Invalid request parameters content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' example: error: "validation_failed" message: "Invalid order quantity: must be positive" request_id: "req_123456" timestamp: "2024-01-15T10:30:00Z" Unauthorized: description: Authentication required content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' example: error: "authentication_required" message: "Valid JWT token required" request_id: "req_123456" timestamp: "2024-01-15T10:30:00Z" Forbidden: description: Insufficient permissions content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' example: error: "permission_denied" message: "Insufficient privileges for this operation" request_id: "req_123456" timestamp: "2024-01-15T10:30:00Z" NotFound: description: Resource not found content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' example: error: "resource_not_found" message: "Order not found" request_id: "req_123456" timestamp: "2024-01-15T10:30:00Z" RiskViolation: description: Risk management violation content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' example: error: "risk_violation" message: "Order exceeds position limit" request_id: "req_123456" timestamp: "2024-01-15T10:30:00Z" details: violation_type: "position_limit" current_position: 1000 position_limit: 500 requested_quantity: 600 RateLimit: description: Rate limit exceeded content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' example: error: "rate_limit_exceeded" message: "Too many requests, try again later" request_id: "req_123456" timestamp: "2024-01-15T10:30:00Z" details: limit: 1000 window_seconds: 60 retry_after: 30 InternalError: description: Internal server error content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' example: error: "internal_error" message: "An unexpected error occurred" request_id: "req_123456" timestamp: "2024-01-15T10:30:00Z"