working version, before optimalization
This commit is contained in:
103
florida/doc/AERODROME_CL_INTEGRATION.md
Normal file
103
florida/doc/AERODROME_CL_INTEGRATION.md
Normal file
@ -0,0 +1,103 @@
|
||||
# Aerodrome Slipstream (CLP) Integration Guide
|
||||
|
||||
This document details the specific technical requirements for integrating **Aerodrome Slipstream** (Concentrated Liquidity) pools into a Uniswap V3-compatible bot. Aerodrome Slipstream is a fork of Uniswap V3 (via Velodrome V2) but introduces critical ABI and logic changes that cause standard implementations to fail.
|
||||
|
||||
## 1. Key Differences from Uniswap V3
|
||||
|
||||
| Feature | Standard Uniswap V3 | Aerodrome Slipstream |
|
||||
| :--- | :--- | :--- |
|
||||
| **Factory Pool Lookup** | `getPool(tokenA, tokenB, fee)` | `getPool(tokenA, tokenB, tickSpacing)` |
|
||||
| **NPM Mint Parameter** | `uint24 fee` | `int24 tickSpacing` |
|
||||
| **NPM Mint Struct** | `MintParams { ..., deadline }` | `MintParams { ..., deadline, sqrtPriceX96 }` |
|
||||
| **Pool Identification** | Fee Tier (e.g., 500, 3000) | Tick Spacing (e.g., 1, 100) |
|
||||
|
||||
## 2. ABI Modifications
|
||||
|
||||
To interact with the Aerodrome `NonfungiblePositionManager` (NPM), you must use a modified ABI. The standard Uniswap V3 NPM ABI will result in revert errors during encoding.
|
||||
|
||||
### MintParams Struct
|
||||
The `MintParams` struct in the `mint` function input must be defined as follows:
|
||||
|
||||
```json
|
||||
{
|
||||
"components": [
|
||||
{"internalType": "address", "name": "token0", "type": "address"},
|
||||
{"internalType": "address", "name": "token1", "type": "address"},
|
||||
{"internalType": "int24", "name": "tickSpacing", "type": "int24"}, // CHANGED from uint24 fee
|
||||
{"internalType": "int24", "name": "tickLower", "type": "int24"},
|
||||
{"internalType": "int24", "name": "tickUpper", "type": "int24"},
|
||||
{"internalType": "uint256", "name": "amount0Desired", "type": "uint256"},
|
||||
{"internalType": "uint256", "name": "amount1Desired", "type": "uint256"},
|
||||
{"internalType": "uint256", "name": "amount0Min", "type": "uint256"},
|
||||
{"internalType": "uint256", "name": "amount1Min", "type": "uint256"},
|
||||
{"internalType": "address", "name": "recipient", "type": "address"},
|
||||
{"internalType": "uint256", "name": "deadline", "type": "uint256"},
|
||||
{"internalType": "uint160", "name": "sqrtPriceX96", "type": "uint160"} // ADDED
|
||||
],
|
||||
"internalType": "struct INonfungiblePositionManager.MintParams",
|
||||
"name": "params",
|
||||
"type": "tuple"
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Python Implementation Strategy
|
||||
|
||||
### A. Configuration
|
||||
When defining the pool configuration, use the **Tick Spacing** value (e.g., 100) where you would normally put the Fee.
|
||||
|
||||
```python
|
||||
"AERODROME_BASE_CL": {
|
||||
"NAME": "Aerodrome SlipStream (Base) - WETH/USDC",
|
||||
"NPM_ADDRESS": "0x827922686190790b37229fd06084350E74485b72", # Aerodrome NPM
|
||||
"POOL_FEE": 100, # Actual TickSpacing (e.g., 100 for volatile, 1 for stable)
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### B. Logic Changes (`clp_manager.py`)
|
||||
|
||||
1. **ABI Selection:** Dynamically switch between Standard and Aerodrome ABIs based on the target DEX.
|
||||
2. **Parameter Construction:** When calling `mint`, check if the target is Aerodrome. If so, append `0` (for `sqrtPriceX96`) to the arguments tuple.
|
||||
|
||||
```python
|
||||
# Pseudo-code for Mint Call
|
||||
base_params = [
|
||||
token0, token1,
|
||||
tick_spacing, # Passed as int24
|
||||
tick_lower, tick_upper,
|
||||
amount0, amount1,
|
||||
amount0_min, amount1_min,
|
||||
recipient,
|
||||
deadline
|
||||
]
|
||||
|
||||
if is_aerodrome:
|
||||
base_params.append(0) # sqrtPriceX96 must be present and 0 for existing pools
|
||||
|
||||
npm_contract.functions.mint(tuple(base_params)).transact(...)
|
||||
```
|
||||
|
||||
### C. Swap Router
|
||||
Aerodrome Slipstream's **SwapRouter** (`0xbe6D...`) uses the `SwapRouter01` ABI style (includes `deadline` in `ExactInputSingleParams`), whereas standard Uniswap V3 on Base often uses `SwapRouter02` (no deadline).
|
||||
|
||||
* **Tip:** For simplicity, you can use the **Standard Uniswap V3 Router** (`0x2626...`) on Base to swap tokens (WETH/USDC) even if you are providing liquidity on Aerodrome, provided the tokens are standard. This avoids ABI headaches with the Aerodrome Router if you only need simple swaps.
|
||||
|
||||
## 4. Troubleshooting Common Errors
|
||||
|
||||
* **`('execution reverted', 'no data')`**:
|
||||
* **Cause 1:** Passing `fee` (uint24) instead of `tickSpacing` (int24).
|
||||
* **Cause 2:** Missing `sqrtPriceX96` parameter in the struct.
|
||||
* **Cause 3:** Tick range (`tickLower`, `tickUpper`) not aligned to the pool's `tickSpacing` (e.g., must be multiples of 100).
|
||||
* **`BadFunctionCallOutput` / `InsufficientDataBytes`**:
|
||||
* **Cause:** Using the wrong Contract Address for the chain (e.g., using Mainnet NPM address on Base).
|
||||
* **Cause:** Calling `factory()` on a contract that doesn't have it (wrong ABI or Proxy).
|
||||
|
||||
## 5. Addresses (Base)
|
||||
|
||||
| Contract | Address |
|
||||
| :--- | :--- |
|
||||
| **Aerodrome NPM** | `0x827922686190790b37229fd06084350E74485b72` |
|
||||
| **Aerodrome Factory** | `0x5e7BB104d84c7CB9B682AaC2F3d509f5F406809A` |
|
||||
| **Uniswap V3 NPM** | `0xC36442b4a4522E871399CD717aBDD847Ab11FE88` |
|
||||
| **WETH** | `0x4200000000000000000000000000000000000006` |
|
||||
| **USDC** | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` |
|
||||
66
florida/doc/CLP_DATA_INTERPRETATION.md
Normal file
66
florida/doc/CLP_DATA_INTERPRETATION.md
Normal file
@ -0,0 +1,66 @@
|
||||
# Interpreting CLP Pool Data
|
||||
|
||||
This guide explains how to read and use the data generated by the **Pool Scanner** and **Analyzer** tools to select the most profitable liquidity pools.
|
||||
|
||||
## 1. The Data Pipeline
|
||||
|
||||
1. **Scanner (`pool_scanner.py`):** Runs continuously. Connects to the blockchain every 10 minutes and records the "Heartbeat" of each pool:
|
||||
* **Tick:** The current price tick.
|
||||
* **FeeGrowthGlobal:** A cumulative counter of all fees earned by the pool since inception.
|
||||
2. **Analyzer (`analyze_pool_data.py`):** Runs on demand. It "replays" the history recorded by the scanner to simulate how a specific strategy (e.g., $10k investment, +/- 10% range) would have performed.
|
||||
|
||||
## 2. Reading the Analyzer Report
|
||||
|
||||
When you run `python tools/analyze_pool_data.py`, you get a table like this:
|
||||
|
||||
```text
|
||||
=== POOL PERFORMANCE REPORT ===
|
||||
Pool Duration Rebalances Final Equity (Est) ROI %
|
||||
Uniswap V3 (Base) - WETH/USDC 1 days 2 10050.00 0.50
|
||||
Aerodrome SlipStream (Base) - WETH/USDC 1 days 0 10010.00 0.10
|
||||
```
|
||||
|
||||
### Key Metrics
|
||||
|
||||
* **Duration:** How long the scanner has been tracking this pool. Longer duration = more reliable data.
|
||||
* **Rebalances:** How many times the price went **Out of Range** (+/- 10%) during this period.
|
||||
* **Low is Good:** Means the price is stable relative to your range. Less work for the bot, fewer fees paid.
|
||||
* **High is Bad:** Means the pool is volatile. You are paying frequent swap/gas fees to move your range.
|
||||
* **Final Equity (Est):** Your simulated $10,000 starting capital after:
|
||||
* (+) Adding estimated Fee Income.
|
||||
* (-) Subtracting Rebalance Costs (0.1% per rebalance).
|
||||
* (+/-) Asset Value Change (Impermanent Loss is inherently captured because we track value in USD).
|
||||
* **ROI %:** The return on investment for the duration.
|
||||
* `0.50%` in 1 day approx `180%` APR (compounded).
|
||||
|
||||
## 3. Selecting a Pool
|
||||
|
||||
Use the report to find the "Sweet Spot":
|
||||
|
||||
| Scenario | Verdict |
|
||||
| :--- | :--- |
|
||||
| **High Fees, Low Rebalances** | **🥇 BEST.** The ideal pool. Price stays in range, volume is high. |
|
||||
| **High Fees, High Rebalances** | **⚠️ RISKY.** You earn a lot, but you burn a lot on swaps/gas. Net profit might be lower than expected. |
|
||||
| **Low Fees, Low Rebalances** | **😴 SAFE.** Good for "set and forget," but returns are meager. |
|
||||
| **Low Fees, High Rebalances** | **❌ AVOID.** You will lose money rebalancing a chop-heavy pool with no volume. |
|
||||
|
||||
## 4. Advanced: Raw Data (`pool_history.csv`)
|
||||
|
||||
If you open the CSV directly, you will see columns like `feeGrowthGlobal0X128`.
|
||||
|
||||
* **Fee Growth:** This number ONLY goes up.
|
||||
* **Speed of Growth:** The faster this number increases, the higher the trading volume (and APR) of the pool.
|
||||
* **Tick:**
|
||||
* `Price = 1.0001 ^ Tick`
|
||||
* Stable Tick = Low Volatility.
|
||||
|
||||
## 5. Simulation Logic
|
||||
|
||||
The Analyzer assumes:
|
||||
1. **Initial Investment:** $10,000 USD.
|
||||
2. **Strategy:** Active Management (Auto-Rebalance).
|
||||
3. **Range:** +/- 10% (Configurable in script).
|
||||
4. **Cost:** 0.1% of capital per rebalance (Swap fee + Gas estimate).
|
||||
5. **Fee Accrual:** You ONLY earn fees when the recorded tick is inside your virtual range.
|
||||
|
||||
*Note: This is a "Paper Trading" simulation. Real-world slippage and exact execution timing may vary.*
|
||||
93
florida/doc/SECURITY_AND_OPTIMIZATION.md
Normal file
93
florida/doc/SECURITY_AND_OPTIMIZATION.md
Normal file
@ -0,0 +1,93 @@
|
||||
# Security & Optimization Protocols
|
||||
|
||||
This document details the safety mechanisms, entry guardrails, and optimization strategies implemented in the Uniswap Auto CLP & Hedger system.
|
||||
|
||||
## 1. CLP Manager: Entry & Position Safety
|
||||
|
||||
The `clp_manager.py` module is responsible for opening and managing Concentrated Liquidity Positions (CLP). It implements strict checks to ensure positions are only opened under favorable conditions.
|
||||
|
||||
### A. Oracle Guard Rail (Anti-Manipulation)
|
||||
**Goal:** Prevent entering a pool that is actively being manipulated (Flash Loans) or has momentarily de-pegged.
|
||||
* **Mechanism:** Before any calculation, the bot fetches the **Real-Time Mid Price** directly from the Hyperliquid API.
|
||||
* **Logic:**
|
||||
* `Pool Price` is calculated from the on-chain `sqrtPriceX96`.
|
||||
* `Oracle Price` is fetched from Hyperliquid (`https://api.hyperliquid.xyz/info`).
|
||||
* **Rule:** If `abs(Pool - Oracle) / Oracle > 0.25%`, the bot **ABORTS** the entry.
|
||||
* **Benefit:** Protects against entering at a "fake" price which would lead to instant arbitrage loss (LVR).
|
||||
|
||||
### B. Stale Tick Protection (Volatility Guard)
|
||||
**Goal:** Prevent entering a position if the price moves significantly during the transaction setup phase (e.g., while swapping tokens).
|
||||
* **Mechanism:**
|
||||
1. The bot calculates the target tick range at $T_0$.
|
||||
2. It performs necessary token swaps (e.g., USDC -> WETH) which takes time ($T_1$).
|
||||
3. **Critical Check:** Just before minting ($T_2$), it re-fetches the current pool tick.
|
||||
* **Rule:** If `abs(Tick_T0 - Tick_T2) > 13 ticks` (approx 0.13%), the bot **ABORTS** the mint transaction.
|
||||
* **Benefit:** Ensures the range is centered on the *actual* execution price, not an outdated one.
|
||||
|
||||
### C. Post-Mint Accuracy
|
||||
**Goal:** Ensure the "Entry Price" recorded for the Hedger is 100% accurate.
|
||||
* **Mechanism:** Immediately after the Mint transaction is confirmed on-chain, the bot fetches the pool state *one more time*.
|
||||
* **Benefit:** Captures the exact price impact of the user's own liquidity insertion, preventing discrepancies in the Hedger's PnL calculations.
|
||||
|
||||
### D. Safe Entry Zones (AUTO Mode)
|
||||
**Goal:** Only enter when mean reversion is statistically likely.
|
||||
* **Mechanism:**
|
||||
* **Bollinger Bands (BB):** Price must be inside the 12h BB.
|
||||
* **Moving Average (MA):** The MA88 must also be inside the 12h BB.
|
||||
* **Benefit:** Avoids opening positions during breakout trends or extreme volatility expansion.
|
||||
|
||||
### E. Manual Override (Force Mode)
|
||||
**Goal:** Allow operator intervention for testing or recovery.
|
||||
* **Command:** `python clp_manager.py --force <width>` (e.g., 0.95).
|
||||
* **Behavior:** Bypasses Oracle, BB, and MA checks for the **first** position only. Automatically disables itself after one successful mint.
|
||||
|
||||
---
|
||||
|
||||
## 2. CLP Hedger: Risk Management
|
||||
|
||||
The `clp_hedger.py` module manages the Delta-Neutral hedge on Hyperliquid.
|
||||
|
||||
### A. Emergency Edge Closure (Stop-Loss)
|
||||
**Goal:** Prevent indefinite hedging losses if the price breaks out of the LP range violently.
|
||||
* **Trigger:** If `Price >= Range Upper Bound`.
|
||||
* **Action:** Immediately **CLOSE** the short hedge position.
|
||||
* **Benefit:** Stops the strategy from "selling low and buying high" (hedging) when the LP position is already out of range and effectively essentially 100% stablecoin (impermanent loss realized).
|
||||
|
||||
### B. Hysteresis Reset
|
||||
**Goal:** Prevent "whipsaw" losses (opening/closing repeatedly) if the price hovers exactly at the edge.
|
||||
* **Logic:** Once an Emergency Closure triggers, the hedge does **not** re-open immediately if the price dips slightly back in.
|
||||
* **Reset Condition:** Price must drop back to a "Safe Zone" (e.g., 75% of the range width or a specific buffer below the edge).
|
||||
* **Benefit:** Filters out noise at the range boundaries.
|
||||
|
||||
### C. Asymmetric Compensation (EAC)
|
||||
**Goal:** Reduce the "Buy High/Sell Low" churn near the edges of the range.
|
||||
* **Mechanism:** The target hedge delta is adjusted (reduced) as the price approaches the boundaries.
|
||||
* **Logic:** `Target Hedge = Pool Delta * (1 - Proximity_Factor)`.
|
||||
* **Benefit:** Softens the impact of entering/exiting the range, preserving capital.
|
||||
|
||||
### D. Fishing Orders (Maker Rebates)
|
||||
**Goal:** Reduce execution costs.
|
||||
* **Mechanism:** Instead of market dumping (Taker fee ~0.035%), the bot places Limit Orders (Maker) slightly away from the spread.
|
||||
* **Logic:** If the price moves favorably, the order fills, earning a rebate (or paying 0 fee). If not filled within `TIMEOUT`, it falls back to a Taker order if the delta drift is critical.
|
||||
|
||||
---
|
||||
|
||||
## 3. Future Improvements (Roadmap)
|
||||
|
||||
### A. WebSocket Integration
|
||||
* **Current:** Polling REST API every 30-300s (or 1s for guard rails).
|
||||
* **Upgrade:** Implement a persistent WebSocket connection to Hyperliquid and the EVM RPC.
|
||||
* **Benefit:** Sub-100ms reaction times to volatility events.
|
||||
|
||||
### B. Multi-Chain Arbitrage Check
|
||||
* **Current:** Checks Hyperliquid vs Pool.
|
||||
* **Upgrade:** Check Binance/Coinbase prices.
|
||||
* **Benefit:** Detects on-chain lag before it happens (CEX leads DEX).
|
||||
|
||||
### C. Dynamic Fee Optimization
|
||||
* **Current:** Fixed `POOL_FEE`.
|
||||
* **Upgrade:** Automatically switch between 0.05% and 0.01% pools based on volatility and volume metrics.
|
||||
|
||||
### D. Smart Rebalance (Inventory Management)
|
||||
* **Current:** Swaps surplus tokens using 1inch/Universal Router.
|
||||
* **Upgrade:** Use CowSwap or CoW intents for MEV-protected rebalancing of large inventory imbalances.
|
||||
Reference in New Issue
Block a user