DeFi Position Tracker
Monitor LP positions, staking rewards, and yield farming across protocols. Calculate impermanent loss, track cost basis, and feed structured data to crypto-tax-agent for tax reporting.
Supported Protocols
| Category | Protocols |
|---|
| DEX LP | Uniswap v2/v3, Curve, Balancer, Velodrome, PancakeSwap |
| Lending |
Aave v2/v3, Compound v2/v3, Euler, Morpho |
| Liquid Staking | Lido (stETH), Rocket Pool (rETH), Frax (sfrxETH) |
| Yield Farming | Convex, Yearn, Beefy, Pendle |
| Bridges/xChain | LayerZero positions, Stargate LPs |
Supported Chains
Ethereum, Arbitrum, Optimism, Base, Polygon, BSC, Avalanche, Fantom, Solana (via Birdeye/Helius).
Core Workflows
1. Full Portfolio Snapshot
Pull all active DeFi positions for a wallet address using DeBank Pro API (most comprehensive):
CODEBLOCK0
Free alternative — Zapper API:
CODEBLOCK1
2. Impermanent Loss Calculator
Formula:
CODEBLOCK2
Where price_ratio = current_price / entry_price for the volatile asset vs stable.
Python implementation:
CODEBLOCK3
Uniswap v3 LP (concentrated liquidity):
Uniswap v3 IL is range-dependent. Use the official SDK or Revert Finance API:
CODEBLOCK4
3. Cost Basis Tracking Per Position
Track entry prices and quantities for accurate P&L and tax reporting:
CODEBLOCK5
IRS treatment (current guidance):
- - Adding liquidity: typically not a taxable event, but track cost basis
- LP fees earned: ordinary income at time of receipt (FMV)
- Removing liquidity: capital gain/loss (proceeds - cost basis)
- Staking rewards: ordinary income at FMV when received
4. Staking Rewards Tracker
CODEBLOCK6
Aave interest accrual:
CODEBLOCK7
5. Multi-Chain Aggregation
Using Moralis Web3 Data API (no API key for public endpoints):
CODEBLOCK8
Using cast (Foundry) for on-chain reads:
CODEBLOCK9
6. Portfolio Summary Output
Standard JSON schema for handoff to crypto-tax-agent and treasury dashboards:
CODEBLOCK10
Tax Handoff to crypto-tax-agent
Export in crypto-tax-agent's expected format:
CODEBLOCK11
Monitoring & Alerts
Aave Health Factor Monitoring
CODEBLOCK12
LP Out-of-Range Detection (Uniswap v3)
# Check if v3 position is still in range (earning fees)
# currentTick within [tickLower, tickUpper] = in range
cast call 0xC36442b4a4522E871399CD717aBDD847Ab11FE88 \
"positions(uint256)(uint96,address,address,address,uint24,int24,int24,uint128,uint256,uint256,uint128,uint128)" \
YOUR_NFT_ID --rpc-url YOUR_RPC
Data Sources Reference
| Tool | Best For | Cost |
|---|
| DeBank Pro API | Most comprehensive, all protocols | $99/mo |
| Zapper API |
Good free tier, Ethereum + L2 | Free tier available |
| Zerion API | Clean data, portfolio-focused | Freemium |
| Moralis | Multi-chain, developer-friendly | Freemium |
| The Graph | Protocol-specific subgraphs | Free |
| Revert Finance | Uniswap v3 concentrated LP analytics | Free |
| Alchemy/Infura | Raw RPC calls | Freemium |
Common Workflows
Monthly portfolio review:
- 1. Pull snapshot via DeBank/Zapper
- Run IL calculator on all LP positions
- Flag any Aave/Compound positions below HF 1.5
- Flag any v3 positions out of range
- Export income events (fees, staking rewards) to crypto-tax-agent
- Generate markdown summary for treasury dashboard
Pre-tax-season export (Q1):
- 1. Pull all 2025 transactions for tracked wallets
- Classify: income events vs capital events
- Calculate cost basis (FIFO default, HIFO optional)
- Reconcile staking rewards (ordinary income)
- Hand off structured JSON to crypto-tax-agent for 8949/Schedule D
New position entry:
- 1. Record entry tx_hash, block, prices at entry
- Calculate cost basis (token values + gas)
- Store in position ledger
- Set monitoring thresholds (IL%, HF, range status)
Not For This Skill
- - Executing trades or transactions — use a wallet/trading skill
- on-chain-payroll — PTIN-backed Moltlaunch service, not ClawHub
- NFT portfolio tracking — different data model and APIs
- CEX holdings (Coinbase, Kraken) — use a CEX API skill or crypto-tax-agent directly
- Real-time price ticker — use a price feed skill
- Bridging or swapping assets — use a transaction execution skill
DeFi 仓位追踪器
跨协议监控LP仓位、质押奖励和收益耕作。计算无常损失,追踪成本基础,并将结构化数据提供给加密税务代理用于税务报告。
支持的协议
| 类别 | 协议 |
|---|
| DEX LP | Uniswap v2/v3, Curve, Balancer, Velodrome, PancakeSwap |
| 借贷 |
Aave v2/v3, Compound v2/v3, Euler, Morpho |
| 流动性质押 | Lido (stETH), Rocket Pool (rETH), Frax (sfrxETH) |
| 收益耕作 | Convex, Yearn, Beefy, Pendle |
| 跨链桥/xChain | LayerZero 仓位, Stargate LP |
支持的链
Ethereum, Arbitrum, Optimism, Base, Polygon, BSC, Avalanche, Fantom, Solana (通过 Birdeye/Helius)。
核心工作流
1. 完整投资组合快照
使用 DeBank Pro API(最全面)拉取钱包地址的所有活跃 DeFi 仓位:
bash
DeBank Pro API — 完整协议仓位
curl -s https://pro-openapi.debank.com/v1/user/all
complexprotocol
list?id=0xYOURWALLET&chain_ids=eth,arb,op,base,matic \
-H AccessKey: YOUR
DEBANKAPI
KEY | jq .[] | {protocol: .name, netusd
value: .netusd
value, positions: .portfolioitem_list}
免费替代方案 — Zapper API:
bash
curl -s https://api.zapper.xyz/v2/balances?addresses[]=0xYOUR_WALLET&networks[]=ethereum&networks[]=arbitrum \
-H Authorization: Basic $(echo -n :YOURZAPPERKEY | base64)
2. 无常损失计算器
公式:
IL% = 2 * sqrt(priceratio) / (1 + priceratio) - 1
其中 priceratio = currentprice / entry_price,针对波动资产与稳定资产。
Python 实现:
python
import math
def impermanentloss(entryprice: float, current_price: float) -> float:
计算 50/50 LP 仓位的无常损失百分比。
参数:
entry_price: 进入 LP 时波动资产的价格(以稳定资产计价)
current_price: 波动资产的当前价格
返回:
以小数表示的无常损失(负值 = 损失)。乘以 100 得到百分比。
示例:
entry_price = 2000 # 进入时 ETH 价格
current_price = 3000 # 当前 ETH 价格
il = impermanent_loss(2000, 3000)
# 返回 ~-0.0203 → -2.03% IL
priceratio = currentprice / entry_price
il = (2 * math.sqrt(priceratio)) / (1 + priceratio) - 1
return il
def lppositionpnl(
token0qty: float, token1qty: float,
token0entry: float, token1entry: float,
token0current: float, token1current: float,
feesearnedusd: float = 0.0
) -> dict:
LP 仓位的完整盈亏分析,包括无常损失和费用。
返回:
包含以下字段的字典: hodlvalue, lpvalue, ilusd, feesearned, net_pnl
hodlvalue = (token0qty token0current) + (token1qty token1_current)
lpvalue = calculatelpvalue(
token0qty, token1qty,
token0entry, token1entry,
token0current, token1current
)
ilusd = lpvalue - hodl_value
netpnl = ilusd + feesearnedusd
return {
hodlvalueusd: hodl_value,
lpvalueusd: lp_value,
ilusd: ilusd,
ilpct: ilusd / hodlvalue if hodlvalue else 0,
feesearnedusd: feesearnedusd,
netpnlusd: net_pnl,
netpnlpct: netpnl / hodlvalue if hodl_value else 0,
}
def calculatelpvalue(t0qty, t1qty, t0entry, t1entry, t0cur, t1_cur):
计算当前价格下恒定乘积 AMM LP 的价值。
k = t0qty * t1qty # 不变量
# 在当前价格下: t0new = sqrt(k * t1cur / t0_cur) — 等等,用进入时的比例重新计算
entryvalue = (t0qty t0entry) + (t1qty t1_entry)
priceratio = t0cur / t0_entry
# AMM 重新平衡: 每一边 = sqrt(initialproduct * priceratio)
t0new = math.sqrt(k * t0cur / t1_cur)
t1new = math.sqrt(k * t1cur / t0_cur)
return (t0new t0cur) + (t1new t1cur)
Uniswap v3 LP(集中流动性):
Uniswap v3 的无常损失与价格范围相关。使用官方 SDK 或 Revert Finance API:
bash
Revert Finance — v3 仓位分析
curl https://api.revert.finance/v1/position?position
id=YOURNFT
ID&chainid=1
3. 每个仓位的成本基础追踪
追踪入场价格和数量,以实现准确的盈亏和税务报告:
python
from dataclasses import dataclass
from datetime import datetime
from typing import List
@dataclass
class LPEntry:
单个 LP 入场事件(添加流动性)。
timestamp: datetime
protocol: str
chain: str
pool: str
token0_symbol: str
token0_qty: float
token0priceusd: float
token1_symbol: str
token1_qty: float
token1priceusd: float
tx_hash: str
gascostusd: float = 0.0
@property
def costbasisusd(self) -> float:
return (self.token0qty * self.token0price_usd +
self.token1qty * self.token1price_usd +
self.gascostusd)
@dataclass
class LPExit:
LP 退出事件(移除流动性)。
timestamp: datetime
protocol: str
chain: str
pool: str
token0qtyreturned: float
token0priceusd: float
token1qtyreturned: float
token1priceusd: float
fees_token0: float
fees_token1: float
tx_hash: str
gascostusd: float = 0.0
@property
def proceeds_usd(self) -> float:
return (self.token0qtyreturned * self.token0priceusd +
self.token1qtyreturned * self.token1priceusd +
self.feestoken0 * self.token0price_usd +
self.feestoken1 * self.token1price_usd -
self.gascostusd)
IRS 处理方式(当前指引):
- - 添加流动性:通常不是应税事件,但需追踪成本基础
- LP 赚取的费用:收到时的普通收入(公允价值)
- 移除流动性:资本利得/损失(收益 - 成本基础)
- 质押奖励:收到时按公允价值的普通收入
4. 质押奖励追踪器
bash
通过 The Graph 拉取质押奖励历史(Lido 示例)
curl -X POST https://api.thegraph.com/subgraphs/name/lidofinance/lido \
-H Content-Type: application/json \
-d {
query: { totalRewards(where: {account: \0xYOUR_WALLET\}, orderBy: block, orderDirection: desc, first: 100) { id totalRewards totalFee block blockTime } }
}
Aave 利息累积:
bash
aToken 余额变化 = 赚取的利息
使用 Aave 子图获取历史余额快照
curl -X POST https://api.thegraph.com/subgraphs/name/aave/protocol-v3 \
-H Content-Type: application/json