# Data Model: Pacifica Multi-Account BTC Wash Trading System **Date**: 2024-12-29 **Feature**: Multi-account wash trading system for BTC pairs **Status**: Complete ## Core Entities ### 1. Account **Purpose**: Represents a single trading account on Pacifica DEX ```typescript interface Account { id: string; // Unique account identifier name: string; // Human-readable account name apiKey: string; // Pacifica API key (encrypted) privateKey: string; // Private key for signing (encrypted) address: string; // Wallet address balance: { total: number; // Total account balance (USD) available: number; // Available balance for trading used: number; // Used balance (margin) }; positions: Position[]; // Current positions riskLimits: RiskLimits; // Account-specific risk limits isActive: boolean; // Whether account is active for trading createdAt: Date; // Account creation timestamp lastUpdated: Date; // Last update timestamp } ``` **Validation Rules**: - `id` must be unique across all accounts - `apiKey` and `privateKey` must be encrypted - `balance.total` must be >= 0 - `balance.available` must be >= 0 - `balance.used` must be >= 0 - `balance.total` must equal `balance.available + balance.used` **State Transitions**: - `inactive` → `active`: Account enabled for trading - `active` → `inactive`: Account disabled for trading - `active` → `suspended`: Account suspended due to risk breach ### 2. WashTradingSession **Purpose**: Represents a coordinated wash trading session across multiple accounts ```typescript interface WashTradingSession { id: string; // Unique session identifier name: string; // Human-readable session name strategy: TradingStrategy; // Trading strategy configuration accounts: string[]; // Array of account IDs participating status: SessionStatus; // Current session status targetVolume: number; // Target volume to generate (BTC) currentVolume: number; // Current volume generated (BTC) startTime: Date; // Session start timestamp endTime?: Date; // Session end timestamp (if completed) duration: number; // Planned session duration (ms) orderPairs: OrderPair[]; // Generated order pairs riskMetrics: RiskMetrics; // Current risk metrics auditLog: AuditEntry[]; // Audit trail createdAt: Date; // Session creation timestamp updatedAt: Date; // Last update timestamp } ``` **Validation Rules**: - `id` must be unique across all sessions - `accounts` must contain at least 2 account IDs - `targetVolume` must be > 0 - `currentVolume` must be >= 0 - `duration` must be > 0 - `startTime` must be <= `endTime` (if both present) **State Transitions**: - `pending` → `active`: Session started - `active` → `paused`: Session paused - `paused` → `active`: Session resumed - `active` → `completed`: Session completed successfully - `active` → `failed`: Session failed - `active` → `cancelled`: Session cancelled ### 3. OrderPair **Purpose**: Represents a matched buy and sell order across different accounts ```typescript interface OrderPair { id: string; // Unique order pair identifier sessionId: string; // Parent session ID buyOrder: Order; // Buy order details sellOrder: Order; // Sell order details status: OrderPairStatus; // Current order pair status volume: number; // Order volume (BTC) price: number; // Order price (USD) expectedProfit: number; // Expected profit from spread actualProfit: number; // Actual profit realized fees: number; // Total fees paid slippage: number; // Actual slippage experienced executionTime: number; // Time to execute (ms) createdAt: Date; // Order pair creation timestamp updatedAt: Date; // Last update timestamp } ``` **Validation Rules**: - `id` must be unique across all order pairs - `buyOrder.accountId` must differ from `sellOrder.accountId` - `volume` must be > 0 - `price` must be > 0 - `buyOrder.side` must be 'buy' - `sellOrder.side` must be 'sell' **State Transitions**: - `pending` → `submitted`: Orders submitted to exchange - `submitted` → `filled`: Both orders filled successfully - `submitted` → `partial`: One or both orders partially filled - `submitted` → `failed`: One or both orders failed - `submitted` → `cancelled`: Orders cancelled ### 4. Order **Purpose**: Represents a single order on Pacifica DEX ```typescript interface Order { id: string; // Unique order identifier accountId: string; // Account that placed the order pairId: string; // Parent order pair ID symbol: string; // Trading pair (e.g., 'BTC/USD') side: 'buy' | 'sell'; // Order side type: 'market' | 'limit'; // Order type size: number; // Order size (BTC) price?: number; // Order price (for limit orders) status: OrderStatus; // Current order status filledSize: number; // Amount filled (BTC) averagePrice?: number; // Average fill price fees: number; // Fees paid slippage: number; // Slippage experienced pacificaOrderId?: string; // Pacifica exchange order ID createdAt: Date; // Order creation timestamp updatedAt: Date; // Last update timestamp } ``` **Validation Rules**: - `id` must be unique across all orders - `size` must be > 0 - `price` must be > 0 (for limit orders) - `filledSize` must be >= 0 and <= `size` - `side` must be either 'buy' or 'sell' - `type` must be either 'market' or 'limit' **State Transitions**: - `pending` → `submitted`: Order submitted to exchange - `submitted` → `filled`: Order completely filled - `submitted` → `partial`: Order partially filled - `submitted` → `cancelled`: Order cancelled - `submitted` → `failed`: Order failed ### 5. TradingStrategy **Purpose**: Defines how wash trading orders are generated and executed ```typescript interface TradingStrategy { id: string; // Unique strategy identifier name: string; // Human-readable strategy name type: StrategyType; // Strategy type symbol: string; // Trading pair (e.g., 'BTC/USD') parameters: { volumeDistribution: 'equal' | 'weighted' | 'random'; priceRange: { min: number; // Minimum price offset (%) max: number; // Maximum price offset (%) }; timing: { minInterval: number; // Minimum interval between orders (ms) maxInterval: number; // Maximum interval between orders (ms) orderSize: { min: number; // Minimum order size (BTC) max: number; // Maximum order size (BTC) }; }; riskLimits: { maxPositionSize: number; // Maximum position size (% of balance) stopLossThreshold: number; // Stop loss threshold (%) maxSlippage: number; // Maximum acceptable slippage (%) }; }; isActive: boolean; // Whether strategy is active createdAt: Date; // Strategy creation timestamp updatedAt: Date; // Last update timestamp } ``` **Validation Rules**: - `id` must be unique across all strategies - `symbol` must be a valid trading pair - `priceRange.min` must be < `priceRange.max` - `timing.minInterval` must be < `timing.maxInterval` - `timing.orderSize.min` must be < `timing.orderSize.max` - All percentage values must be between 0 and 100 ### 6. RiskMetrics **Purpose**: Tracks risk metrics for a trading session ```typescript interface RiskMetrics { sessionId: string; // Parent session ID totalExposure: number; // Total exposure across all accounts maxDrawdown: number; // Maximum drawdown experienced currentDrawdown: number; // Current drawdown sharpeRatio: number; // Risk-adjusted return ratio volatility: number; // Price volatility correlation: number; // Correlation between accounts riskScore: number; // Overall risk score (0-100) alerts: RiskAlert[]; // Active risk alerts lastUpdated: Date; // Last update timestamp } ``` **Validation Rules**: - `totalExposure` must be >= 0 - `maxDrawdown` must be >= 0 - `currentDrawdown` must be >= 0 - `riskScore` must be between 0 and 100 - `correlation` must be between -1 and 1 ### 7. RiskAlert **Purpose**: Represents a risk management alert ```typescript interface RiskAlert { id: string; // Unique alert identifier sessionId: string; // Parent session ID type: RiskAlertType; // Alert type severity: 'low' | 'medium' | 'high' | 'critical'; message: string; // Alert message threshold: number; // Threshold that was breached currentValue: number; // Current value accountId?: string; // Account ID (if account-specific) isAcknowledged: boolean; // Whether alert was acknowledged createdAt: Date; // Alert creation timestamp acknowledgedAt?: Date; // Acknowledgment timestamp } ``` **Validation Rules**: - `id` must be unique across all alerts - `severity` must be one of the defined levels - `message` must not be empty - `threshold` must be > 0 - `currentValue` must be >= 0 ### 8. AuditEntry **Purpose**: Represents an audit log entry for compliance and debugging ```typescript interface AuditEntry { id: string; // Unique audit entry identifier sessionId: string; // Parent session ID action: string; // Action performed details: any; // Action details accountId?: string; // Account ID (if applicable) orderId?: string; // Order ID (if applicable) timestamp: Date; // Action timestamp userId?: string; // User ID (if applicable) } ``` **Validation Rules**: - `id` must be unique across all audit entries - `action` must not be empty - `timestamp` must be valid date - `details` must be serializable ## Enums and Types ### SessionStatus ```typescript type SessionStatus = 'pending' | 'active' | 'paused' | 'completed' | 'failed' | 'cancelled'; ``` ### OrderPairStatus ```typescript type OrderPairStatus = 'pending' | 'submitted' | 'filled' | 'partial' | 'failed' | 'cancelled'; ``` ### OrderStatus ```typescript type OrderStatus = 'pending' | 'submitted' | 'filled' | 'partial' | 'cancelled' | 'failed'; ``` ### StrategyType ```typescript type StrategyType = 'equal_volume' | 'time_based' | 'market_making' | 'custom'; ``` ### RiskAlertType ```typescript type RiskAlertType = 'position_size' | 'drawdown' | 'slippage' | 'margin' | 'correlation' | 'volatility'; ``` ## Entity Relationships ### Primary Relationships - **WashTradingSession** → **Account** (many-to-many via accounts array) - **WashTradingSession** → **OrderPair** (one-to-many) - **OrderPair** → **Order** (one-to-many, exactly 2) - **Order** → **Account** (many-to-one) - **WashTradingSession** → **TradingStrategy** (many-to-one) - **WashTradingSession** → **RiskMetrics** (one-to-one) - **RiskMetrics** → **RiskAlert** (one-to-many) - **WashTradingSession** → **AuditEntry** (one-to-many) ### Data Flow 1. **Session Creation**: WashTradingSession created with strategy and accounts 2. **Order Generation**: Strategy generates OrderPair instances 3. **Order Execution**: Orders submitted to Pacifica DEX 4. **Status Updates**: Order and OrderPair statuses updated via WebSocket 5. **Risk Monitoring**: RiskMetrics updated continuously 6. **Audit Logging**: All actions logged in AuditEntry instances ## Data Validation Rules ### Cross-Entity Validation - Account balance must be sufficient for order size - Order pair must maintain position neutrality across accounts - Session target volume must be achievable with available account balances - Risk limits must be respected across all active sessions ### Business Logic Validation - Maximum 20 accounts per session - Minimum 2 accounts per session - Order pairs must be executed atomically - Risk alerts must be acknowledged before session can continue - All trading activities must be audited ## Data Persistence Strategy ### In-Memory Storage - Active sessions and order pairs - Real-time risk metrics - WebSocket connection states - Account balances and positions ### Persistent Storage - Account configurations (encrypted) - Trading strategies - Audit logs - Session history - Risk alert history ### Data Cleanup - In-memory data cleaned up when sessions end - Audit logs retained for compliance (configurable retention period) - Old sessions archived after completion - Risk alerts archived after acknowledgment ## Performance Considerations ### Data Structure Optimization - Use Maps for O(1) lookups by ID - Use Sets for account membership checks - Use arrays for ordered collections (order pairs, audit entries) - Implement efficient filtering and sorting ### Memory Management - Limit in-memory session count - Implement data pagination for large collections - Use weak references where appropriate - Monitor memory usage and implement cleanup ### Query Optimization - Index frequently queried fields - Implement efficient filtering algorithms - Use batch operations for bulk updates - Cache frequently accessed data