# Unified Delta-Neutral Hedger Logic ## 1. Overview The **Unified Hedger** (`unified_hedger.py`) is the central risk management engine for the Auto CLP system. Unlike the previous architecture where each LP position required a separate process, this unified system manages **all** Liquidity Pool positions across different chains (Arbitrum, BNB Chain, Base) in a single, efficient process. ### Architecture Comparison **Old Architecture (Multi-Process):** ```mermaid graph TD A[Manager Arbitrum] -->|Write| B(UNISWAP_V3_status.json) C[Manager BNB] -->|Write| D(PANCAKESWAP_BNB_status.json) B -->|Read| E[Hedger Process 1] D -->|Read| F[Hedger Process 2] E -->|API Call| G[Hyperliquid] F -->|API Call| G style E fill:#f96,stroke:#333 style F fill:#f96,stroke:#333 ``` **New Architecture (Unified):** ```mermaid graph TD A[Manager Arbitrum] -->|Write| B(UNISWAP_V3_status.json) C[Manager BNB] -->|Write| D(PANCAKESWAP_BNB_status.json) B -->|Read| E[Unified Hedger (Master)] D -->|Read| E E -->|Single API Connection| G[Hyperliquid] style E fill:#9f9,stroke:#333 ``` --- ## 2. Core Logic Flow The hedger runs a continuous loop (approx. every 1 second) performing the following steps: ```mermaid sequenceDiagram participant Loop as Main Loop participant Scanner as Strategy Scanner participant API as Hyperliquid API participant Math as Aggregation Engine participant Exec as Execution Logic Loop->>Scanner: Scan *_status.json files Scanner-->>Loop: Update Active Strategies Loop->>API: Fetch All Prices & Account State (Once) API-->>Loop: Market Data & Balances loop For Each Strategy Loop->>Math: Calculate Ideal Short Size end Math->>Math: Netting (Sum Targets by Coin) Loop->>Exec: Compare Net Target vs. Actual Position alt Diff > Threshold Exec->>API: Place Order (Buy/Sell) Exec->>Loop: Sleep 5s (API Lag Safety) else Diff < Threshold Exec->>Loop: Do Nothing (Idle) end ``` --- ## 3. Detailed Mechanisms ### A. Strategy Scanning & Initialization * **Discovery:** The script uses `glob` to find all files matching `*_status.json` in the project directory. * **Parsing:** It loads the JSON and extracts active positions (`OPEN`, `PENDING_HEDGE`). * **Liquidity Scaling:** To support different chains with different decimals (e.g., BNB has 18 decimals, USDC has 6), it calculates a scaling factor: $$ Scale = 10^{-(d_0 + d_1)/2} $$ This ensures the liquidity math ($L$) is normalized for the hedging calculations. ### B. Ideal Delta Calculation For each active LP position, the strategy calculates how much it *should* be short to be delta-neutral. Formula for Concentrated Liquidity Delta ($\Delta_{LP}$): $$ \Delta_{LP} = L \times \left( \frac{1}{\sqrt{P_{current}}} - \frac{1}{\sqrt{P_{upper}}} \right) $$ * If $P_{current} < P_{lower}$: Delta is max (full range). * If $P_{current} > P_{upper}$: Delta is 0. ### C. Portfolio Netting (The "Alpha") This is the key efficiency gain. Instead of trading for every position, the system sums up the requirements. | Strategy | Chain | Coin | Ideal Short | | :--- | :--- | :--- | :--- | | Strat A | Arbitrum | ETH | -1.5 ETH | | Strat B | Base | ETH | -0.5 ETH | | Strat C | Arbitrum | ETH | +0.2 ETH (Long/Closing) | | **NET TOTAL** | **ALL** | **ETH** | **-1.8 ETH** | The hedger only checks the Hyperliquid account once: * **Reality:** Account has `-1.6 ETH` short. * **Action:** Sell `0.2 ETH` to reach `-1.8`. * *Result:* Strat C's "Buy" was internally netted against Strat A's "Sell". **Zero fees paid for that portion.** ### D. Execution & Thresholds The decision to trade is based on a dynamic threshold system to avoid churn (over-trading). 1. **Volatility Adjustment:** It calculates the standard deviation of the last 30 price points. $$ Threshold_{Dynamic} = BaseThreshold \times \min(3.0, \frac{Vol_{Current}}{Vol_{Base}}) $$ *High Volatility = Wider Thresholds (Trade less).* 2. **Edge Protection:** If the price is very close to the range boundary (e.g., within 2%), the math becomes unstable (Gamma spike). * **Action:** Force the threshold to the minimum (`MIN_HEDGE_THRESHOLD`) to ensure precise hedging at the dangerous "exit" zones. 3. **Safety Checks:** * **Large Hedge Multiplier (5.0x):** If the required trade size is huge (>5x normal threshold), it assumes a "Catch-up" is needed but treats it carefully. * **API Lag Sleep:** After *any* trade, the loop **sleeps for 5 seconds**. This prevents the "Double Hedge" bug where the bot trades again because the API hasn't updated the position size yet. ### E. Shadow Orders Since the bot often uses Taker orders (Market/IOC) during urgent rebalances, it simulates "What if I had used a Maker order?". * It creates a virtual "Shadow Order" in memory. * It tracks the order book. If the price crosses the shadow price, it marks it as "Filled". * *Purpose:* To gather data on whether a purely Maker-based strategy would be viable in the future. --- ## 4. Configuration Reference All settings are tunable in `unified_hedger.py` or via `clp_config.py`. | Parameter | Default | Description | | :--- | :--- | :--- | | `LARGE_HEDGE_MULTIPLIER` | `5.0` | Multiplier for "Urgent" trade flag. Higher = Less Panic. | | `MIN_TIME_BETWEEN_TRADES` | `60s` | Cooldown for standard rebalances. | | `BASE_REBALANCE_THRESHOLD_PCT` | `0.09` | 9% deviation allowed before rebalancing (scaled by Vol). | | `ENABLE_EDGE_CLEANUP` | `True` | Forces tight hedging at range edges. |