Cl Lp Rebalancer

SkillDB 作者 SynthThoughts v3.9.1

Uniswap V3 集中流动性 LP 自动调仓策略。基于波动率自适应范围宽度:低波动率收紧范围(高资本效率),高波动率放宽范围(减少调仓和 IL)。支持趋势不对称调整、多时间框架分析、自动 claim/remove/swap/deposit 全流程。适用于 EVM L2 链上 CL LP 管理、调仓、范围优化、手续费最大化场景。用户查询收益、PnL、仓位、头寸状态、LP 状况、年化、手续费、无常损失时,调用 status 子命令即可获取(每 5 分钟缓存一次,秒级响应)。

源码 ↗

安装 / 下载方式

TotalClaw CLI推荐
totalclaw install skilldb:synththoughts~cl-lp-rebalancer
cURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/skilldb%3Asynththoughts~cl-lp-rebalancer/file -o cl-lp-rebalancer.md
Git 仓库获取源码
git clone https://github.com/openclaw/skills/commit/c37e3e771e05de17bf74bc60f4f652f0191f2399
# CL LP Auto-Rebalancer v1

Cron 驱动的 Uniswap V3 集中流动性自动调仓机器人,运行在 EVM L2 链上,通过 `onchainos` CLI 执行 DeFi 操作。核心思路:**波动率决定范围宽度** — 低波动率时收紧范围提高资本效率,高波动率时放宽范围减少调仓频率和无常损失。

每个 tick:获取价格 → 波动率分析 → 范围计算 → 调仓决策 → 执行调仓 → 报告。

## Architecture

```
Cron (5min) → Python script → onchainos CLI → OKX Web3 API → Chain
                  ↓                ↓
            cl_lp_state.json    Wallet (TEE signing)
                  ↓
            ┌──────────────┐
            │ Price Fetch   │ ← onchainos swap quote / market price
            │ K-line ATR    │ ← onchainos market kline (1H × 24)
            │ MTF Analysis  │ ← price_history (288 bars = 24h)
            └──────┬───────┘
                   ↓
            Range Calculation (vol-adaptive)
                   ↓
            Rebalance Decision
                   ↓
            ┌──────────────┐
            │ Claim Fees    │ ← onchainos defi claim
            │ Remove Liq    │ ← onchainos defi redeem
            │ Swap Ratio    │ ← onchainos swap swap
            │ Add Liq       │ ← onchainos defi deposit
            └──────┬───────┘
                   ↓
            Structured JSON output
```

**OKX Skill Dependencies** (via `onchainos` CLI — 处理认证、链解析、错误重试):

- Price: `onchainos market price --address <token> --chain <chain>`
- K-line: `onchainos market kline --address <token> --chain <chain> --bar 1H --limit 24`
- Quote: `onchainos swap quote --from <A> --to <B> --amount <amt> --chain <chain>`
- Swap: `onchainos swap swap --from <A> --to <B> --amount <amt> --chain <chain> --wallet <addr> --slippage <pct>`
- Approve: `onchainos swap approve --token <addr> --amount <amt> --chain <chain>`
- Pool Search: `onchainos defi search --chain <chain> --token "<token0>,<token1>" --product-group DEX_POOL`
- Pool Detail: `onchainos defi detail --investment-id <id> --chain <chain>`
- Calculate Entry: `onchainos defi calculate-entry --investment-id <id> --chain <chain> --tick-lower <tick> --tick-upper <tick>`
- Deposit: `onchainos defi deposit --investment-id <id> --chain <chain> --amount0 <amt> --amount1 <amt> --tick-lower <tick> --tick-upper <tick>`
- Redeem: `onchainos defi redeem --investment-id <id> --chain <chain> --token-id <id> --percent 100`
- Claim Fees: `onchainos defi claim --investment-id <id> --chain <chain> --token-id <id>`
- Positions: `onchainos defi positions --chain <chain>`
- Position Detail: `onchainos defi position-detail --investment-id <id> --chain <chain> --token-id <id>`

## Step 0: Pool Selection (First-Time Setup)

When user has no `config.json` or asks to set up a new pool, trigger this step.

**核心原则**:AI 应从用户的自然语言中提取意图,自动推断尽可能多的参数,只在信息不足时才追问。

### 0.1 Intent Recognition

从用户输入中提取:

| 信息 | 示例用户输入 | 提取结果 |
|------|------------|---------|
| 链 | "在 Base 上做 LP" | chain = base |
| 代币对 | "ETH/USDC 的流动性" | token0 = ETH, token1 = USDC |
| 风险偏好 | "稳定一点的" | pool_type = stablecoin |
| Fee tier | "0.3% 的池子" | fee_tier = 0.3% |

**缺失信息的默认推断**:
- 未指定链 → 推荐 Base(L2 gas 低,适合频繁调仓)
- 未指定代币对 → 必须追问(核心参数,无法推断)
- 未指定 fee tier → 根据代币对自动选 TVL 最大的池子
- 未指定风险偏好 → 从代币对自动分类

### 0.2 Pool Type Classification

根据代币对自动分类,**不需要问用户**:

| 类型 | 判断规则 | 默认参数集 |
|------|---------|-----------|
| **稳定币对** | 两个都是稳定币(USDC/USDT/DAI/FRAX) | 窄范围、低止损 |
| **Native/稳定币** | 一个是 ETH/WETH/WBTC,另一个是稳定币 | 标准参数 |
| **非稳定币对** | 两个都不是稳定币,但都是主流币 | 宽范围、高止损 |
| **含 Meme 币** | 代币不在主流币列表中(市值低、无 Coingecko 排名) | 极宽范围 + 强制风险确认 |

主流币白名单:ETH, WETH, WBTC, USDC, USDT, DAI, FRAX, ARB, OP, MATIC, BNB, AVAX, SOL

### 0.3 Meme Coin Risk Gate

**仅当检测到 meme/低市值代币时触发**。MUST display warning before proceeding:

```
⚠️ Meme 币 LP 额外风险:
1. 极端无常损失 — 价格可能单方向暴涨/暴跌 90%+
2. 流动性枯竭 — 池子 TVL 可能骤降,头寸无法退出
3. 合约风险 — 代币可能有 honeypot/税收/暂停转账等恶意机制
4. 调仓失败 — 低流动性导致 swap 滑点过大
```

Must get explicit user confirmation before proceeding.

### 0.4 Search, Rank & Auto-Select

```bash
onchainos defi search --chain <chain> --token "<token0>,<token1>" --product-group DEX_POOL
```

**自动选择逻辑**(用户无需手动选):
1. 按 TVL 降序排列
2. 如果用户指定了 fee tier → 直接匹配
3. 如果未指定 → 选 TVL 最大的池子(通常是最佳流动性)
4. 展示选择结果供用户确认:池名、fee tier、TVL、预估池 APY(`rate` 字段)

**Fee tier 参考**(仅在用户问及或多池需选择时展示):
- 0.01%: 稳定币对 · 0.05%: 高相关性对 · 0.3%: 主流对(推荐)· 1%: 高波动对

### 0.5 Generate config.json

自动 fetch detail (`onchainos defi detail`) 并生成 config,**无需用户手动填写**。

**字段映射**:
- `investment_id` ← search `investmentId`
- `chain_id` ← search `chainIndex`
- `platform_id` ← detail `analysisPlatformId`(注意不是 `platformId`)
- `fee_tier` ← search `feeRate`
- `tick_spacing` ← 根据 fee tier 推导:0.01%→1, 0.05%→10, 0.3%→60, 1%→200
- `token0/token1` ← detail `underlyingToken`。如果 token 是 native ETH(`0xeee...`),LP 合约用 WETH,需映射(Base: `0x4200000000000000000000000000000000000006`)
- `native_token` ← 始终 `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee`(用于 swap 和余额查询)
- 其余参数 ← 根据 pool type 自动填入下表默认值

```json
{
  "investment_id": "<auto>",
  "pool_chain": "<auto>",
  "chain_id": "<auto>",
  "platform_id": "<auto>",
  "native_token": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
  "fee_tier": "<auto>",
  "tick_spacing": "<auto>",
  "token0": { "symbol": "<auto>", "address": "<auto>", "decimals": "<auto>" },
  "token1": { "symbol": "<auto>", "address": "<auto>", "decimals": "<auto>" },
  "range_mult": { "low": 1.0, "medium": 1.2, "high": 1.5, "extreme": 2.0 },
  "min_range_pct": 2,
  "max_range_pct": 5,
  "asym_factor": 0.3,
  "min_position_age_seconds": 3600,
  "max_rebalances_24h": 6,
  "gas_to_fee_ratio": 0.5,
  "max_il_tolerance_pct": 5.0,
  "edge_proximity_threshold": 0.15,
  "stop_loss_pct": 0.15,
  "trailing_stop_pct": 0.1,
  "slippage_pct": 1,
  "gas_reserve_eth": 0.02,
  "min_trade_usd": 5.0,
  "quiet_interval_seconds": 1800,
  "max_consecutive_errors": 5,
  "cooldown_after_errors_seconds": 3600
}
```

**Pool-type-specific defaults**(自动应用,无需用户选择):

| Parameter | 稳定币对 | Native/稳定币 | 非稳定币 | Meme 池 |
|-----------|---------|-------------|---------|---------|
| `min_range_pct` | 0.5 | 2 | 3 | 5 |
| `max_range_pct` | 2 | 5 | 8 | 15 |
| `range_mult.low` | 0.5 | 1.0 | 1.2 | 1.5 |
| `range_mult.extreme` | 1.0 | 2.0 | 2.5 | 3.0 |
| `stop_loss_pct` | 0.05 | 0.15 | 0.20 | 0.30 |
| `trailing_stop_pct` | 0.03 | 0.10 | 0.15 | 0.20 |
| `max_il_tolerance_pct` | 1.0 | 5.0 | 8.0 | 15.0 |
| `gas_reserve_eth` | 0.005 | 0.02 | 0.02 | 0.02 |

### 0.6 Gate

- [ ] `config.json` written with valid `investment_id`, `token0`, `token1`
- [ ] `.env` configured (copy from `.env.example`, fill in API credentials + `WALLET_ADDR`)
- [ ] `onchainos wallet balance` returns valid balances for the target chain
- [ ] If meme pool: user has explicitly confirmed risk warning

---

## Pipeline: Runtime Steps

**CRITICAL RULE**: Steps MUST execute in order. Do NOT skip steps or proceed past a gate that has not been satisfied.

### Step 1: Data Acquisition

**Actions**:
1. Fetch current price via `onchainos market price` or `onchainos swap quote`
2. Fetch current position detail via `onchainos defi position-detail` (if position exists)
3. Update `price_history` (append, cap at 288 = 24h @ 5min)
4. Fetch on-chain balances via `onchainos wallet balance`

**Gate** (ALL must pass):
- [ ] Price is non-null and > 0
- [ ] Circuit breaker not active (`consecutive_errors < 5`)
- [ ] Stop not triggered (`stop_triggered == null`)

### Step 2: Volatility & Trend Analysis

**Actions**:
1. Fetch K-line data (1H candles, 24 bars) → compute ATR-based volatility (hourly cache)
2. Classify volatility: low (<1.5%), medium (1.5-3%), high (3-5%), extreme (>5%)
3. Compute multi-timeframe trend analysis (复用 grid-trading MTF):
   - Short EMA (25min), Medium EMA (1h), Long EMA (4h)
   - EMA alignment → trend direction (bullish/bearish/neutral) + strength (0-1)
   - 8h structure detection (uptrend/downtrend/ranging)
4. Compute 1h and 4h momentum

**Output**: `atr_pct` float, `vol_class` string, `mtf` dict

**Gate**:
- [ ] `atr_pct` is non-null and > 0
- [ ] `vol_class` is one of: low, medium, high, extreme
- [ ] `mtf` dict has `trend` and `strength` fields (graceful fallback to neutral)

### Step 3: Range Calculation

**Actions**:
1. Compute range width based o