# Account Management API Contracts **Feature**: Pacifica Multi-Account Hedging System **Date**: 2024-12-19 **Status**: Complete ## Account Management Endpoints ### 1. Add Account **Endpoint**: `POST /accounts` **Purpose**: Add a new trading account to the system **Request Schema**: ```typescript interface AddAccountRequest { name: string; // Account name (3-30 chars) privateKey: string; // Encrypted private key initialUSDC: number; // Initial USDC balance riskLimits: { maxPositionSize: number; // Max position size (0-1) maxDailyLoss: number; // Max daily loss (0-1) maxLeverage: number; // Max leverage (≥1) stopLossThreshold: number; // Stop loss threshold (0-1) maxSlippage: number; // Max slippage (≥0) minMarginRatio: number; // Min margin ratio (0-1) }; } ``` **Response Schema**: ```typescript interface AddAccountResponse { success: boolean; account: { id: string; name: string; publicKey: string; balance: { usdc: number; margin: number; }; riskLimits: RiskLimits; isActive: boolean; createdAt: string; // ISO timestamp }; message?: string; } ``` **Validation Rules**: - Account name: 3-30 characters, alphanumeric - Private key: Valid encrypted format - Initial USDC: Positive number - Risk limits: All values within valid ranges **Error Responses**: - `400 Bad Request`: Invalid input data - `409 Conflict`: Account name already exists - `500 Internal Server Error`: System error ### 2. List Accounts **Endpoint**: `GET /accounts` **Purpose**: Retrieve all configured accounts **Request Schema**: None (query parameters optional) **Response Schema**: ```typescript interface ListAccountsResponse { success: boolean; accounts: Array<{ id: string; name: string; publicKey: string; balance: { usdc: number; margin: number; }; riskLimits: RiskLimits; isActive: boolean; createdAt: string; lastUpdated: string; }>; total: number; } ``` **Query Parameters**: - `active`: Filter by active status (boolean) - `limit`: Maximum number of accounts to return (number) - `offset`: Number of accounts to skip (number) ### 3. Get Account Details **Endpoint**: `GET /accounts/{id}` **Purpose**: Retrieve detailed information for a specific account **Request Schema**: Account ID in URL path **Response Schema**: ```typescript interface GetAccountResponse { success: boolean; account: { id: string; name: string; publicKey: string; balance: { usdc: number; margin: number; totalValue: number; }; positions: Array<{ id: string; symbol: string; side: 'long' | 'short'; size: number; entryPrice: number; markPrice: number; pnl: number; margin: number; liquidationPrice: number; }>; riskLimits: RiskLimits; isActive: boolean; createdAt: string; lastUpdated: string; }; } ``` **Error Responses**: - `404 Not Found`: Account not found - `500 Internal Server Error`: System error ### 4. Update Account Risk Limits **Endpoint**: `PUT /accounts/{id}/risk-limits` **Purpose**: Update risk management parameters for an account **Request Schema**: ```typescript interface UpdateRiskLimitsRequest { riskLimits: { maxPositionSize?: number; // Optional updates maxDailyLoss?: number; maxLeverage?: number; stopLossThreshold?: number; maxSlippage?: number; minMarginRatio?: number; }; } ``` **Response Schema**: ```typescript interface UpdateRiskLimitsResponse { success: boolean; account: { id: string; riskLimits: RiskLimits; lastUpdated: string; }; message?: string; } ``` **Validation Rules**: - At least one risk limit must be provided - All provided values must be within valid ranges - Changes take effect immediately ### 5. Remove Account **Endpoint**: `DELETE /accounts/{id}` **Purpose**: Remove an account from the system **Request Schema**: Account ID in URL path **Response Schema**: ```typescript interface RemoveAccountResponse { success: boolean; message: string; } ``` **Validation Rules**: - Account must not have active positions - Account must not be part of active hedging sessions - Confirmation required for accounts with trading history **Error Responses**: - `400 Bad Request`: Account has active positions or sessions - `404 Not Found`: Account not found - `500 Internal Server Error`: System error ### 6. Get Portfolio Overview **Endpoint**: `GET /portfolio` **Purpose**: Retrieve aggregated portfolio information across all accounts **Request Schema**: None **Response Schema**: ```typescript interface PortfolioResponse { success: boolean; portfolio: { totalValue: number; totalPnl: number; totalMargin: number; totalVolume: number; accountCount: number; positions: Array<{ symbol: string; netSize: number; avgEntryPrice: number; totalPnl: number; }>; riskMetrics: { maxDrawdown: number; sharpeRatio: number; var95: number; }; lastUpdated: string; }; } ``` ## Error Handling ### Standard Error Response ```typescript interface ErrorResponse { success: false; error: { code: string; // Error code message: string; // Human-readable message details?: any; // Additional error details }; timestamp: string; // ISO timestamp } ``` ### Common Error Codes - `VALIDATION_ERROR`: Input validation failed - `ACCOUNT_NOT_FOUND`: Account does not exist - `ACCOUNT_EXISTS`: Account name already exists - `INSUFFICIENT_BALANCE`: Not enough balance for operation - `RISK_LIMIT_EXCEEDED`: Risk limit would be exceeded - `SYSTEM_ERROR`: Internal system error ## Rate Limiting ### Limits - 100 requests per minute per client - Burst limit: 10 requests per second - Rate limit headers included in responses ### Headers ``` X-RateLimit-Limit: 100 X-RateLimit-Remaining: 95 X-RateLimit-Reset: 1640995200 ``` ## Authentication ### API Key Authentication - Required for all endpoints - Passed in `Authorization` header - Format: `Bearer ` ### Request Signing - All requests must be signed with account private key - Signature included in `X-Signature` header - Prevents request tampering and replay attacks ## Data Validation ### Input Validation - All input data validated against schemas - Type checking for all parameters - Range validation for numeric values - Format validation for strings ### Business Logic Validation - Account balance consistency checks - Risk limit validation - Position size validation - Cross-account coordination validation ## Response Format ### Success Response - `success: true` for successful operations - Data included in response body - Appropriate HTTP status codes (200, 201, 204) ### Error Response - `success: false` for failed operations - Error details in standardized format - Appropriate HTTP status codes (400, 404, 500) ## Versioning ### API Version - Current version: v1 - Version specified in URL: `/api/v1/accounts` - Backward compatibility maintained ### Schema Evolution - New fields added as optional - Deprecated fields marked but not removed - Breaking changes require version bump