Skip to main content
Coming Soon - This feature is currently under development. Stay tuned!
This document introduces how to use ChainStream to monitor DeFi protocol activities, including liquidity changes, large trades, yield tracking, and risk alerts.

Supported DeFi Protocols

DEX (Decentralized Exchanges)

ProtocolChainsSupported Features
Uniswap V2/V3Ethereum, Polygon, Arbitrum, BaseTrading, LP, Pool data
PancakeSwapBSCTrading, LP, Pool data
SushiSwapMulti-chainTrading, LP
RaydiumSolanaTrading, LP
JupiterSolanaAggregated trading
CurveEthereum, Multi-chainStablecoin trading, LP

Lending Protocols

ProtocolChainsSupported Features
Aave V3Ethereum, Polygon, ArbitrumLending, Liquidation, Rates
Compound V3Ethereum, BaseLending, Liquidation
VenusBSCLending, Liquidation
MorphoEthereumLending optimization

Yield Aggregators

ProtocolChainsSupported Features
Yearn FinanceEthereumVault strategies, Yields
Convex FinanceEthereumCurve LP enhancement
Beefy FinanceMulti-chainAuto-compounding

Liquid Staking

ProtocolChainsSupported Features
LidoEthereumETH staking
Rocket PoolEthereumETH staking
MarinadeSolanaSOL staking

Monitoring Dimensions

1. Liquidity Monitoring

Monitored Events

EventDescriptionImportance
pool_createdNew pool creationDiscover new opportunities
liquidity_addAdd liquidityConfidence indicator
liquidity_removeRemove liquidity⚠️ Rug pull warning
pool_updatePool parameter changesProtocol governance

Key Metrics

MetricDescriptionHealthy Standard
TVLTotal Value LockedStable or growing
TVL Change Rate24h/7d TVL change> -10%/day
LP Holder CountLP Token holder distributionDispersed is better
Liquidity DepthLiquidity within ±2% price rangeGreater depth is better

Rug Pull Risk Signals

  • Single withdrawal > 30% of pool
  • 24h cumulative withdrawal > 50%
  • LP concentrated in few addresses (< 5)

2. Trading Monitoring

Real-time Trading Flow

Subscribe to real-time trades via WebSocket:
Event TypeDescriptionData Fields
swapDEX tradetoken_in, token_out, amount, price
large_tradeLarge tradethreshold, trade_details
arbitrageArbitrage tradeprofit, path
mevMEV-related tradetype, extracted_value
// Subscribe to DEX trading flow
ws.subscribe('defi_trades', {
  protocol: 'uniswap_v3',
  chain: 'ethereum',
  min_amount_usd: 10000
}, (trade) => {
  console.log(`${trade.type}: ${trade.token_in}${trade.token_out}`);
});

Trading Analysis Dimensions

Analysis DimensionMetricSignificance
Buy/Sell PressureBuy volume/Sell volume ratio> 1 bullish
Volume TrendVolume moving averageActivity level
Whale BehaviorLarge trade percentageMarket impact
Pair PopularityTrading frequency rankingMarket attention

3. Yield Tracking

Tracked Content

Yield TypeDescriptionCalculation Method
LP MiningTrading fees from providing liquidityFees × Share percentage
Lending InterestDeposit/borrow interestPrincipal × APY
Staking RewardsProtocol token rewardsStaked amount × Reward rate
Airdrop YieldsProtocol airdropsSnapshot holdings

Yield Metrics

MetricDescriptionNotes
APYAnnual Percentage Yield (with compounding)Actual yield reference
APRAnnual Percentage Rate (without compounding)Base yield
Impermanent LossLP loss relative to holdingImportant risk factor
Net YieldYield - Gas - Impermanent LossFinal yield

Impermanent Loss Estimation

Impermanent Loss Formula
Impermanent Loss = 2 × √(Price Ratio) / (1 + Price Ratio) - 1
Price ChangeImpermanent Loss
±10%-0.11%
±25%-0.64%
±50%-2.02%
±100%-5.72%
±200%-13.4%

4. Risk Alerts

Protocol-Level Risks

Risk TypeDescriptionAlert Trigger
Large WithdrawalSignificant liquidity reductionSingle > 5% of pool
TVL PlungeRapid protocol TVL decline> 20% decline in 1h
Flash Loan AttackFlash loan pattern detectedAuto-detection
Governance AttackAbnormal proposals or votesAuto-detection
Oracle AnomalyAbnormal price dataDeviation > 5%

Position-Level Risks

Risk TypeDescriptionAlert Trigger
Liquidation RiskLending position near liquidationHealth factor < 1.2
Impermanent LossLP impermanent loss expandingLoss > 5%
Yield DeclineSignificant APY dropDecline > 50%

Alert Configuration Example

{
  "alert_type": "liquidity_remove",
  "protocol": "uniswap_v3",
  "pool": "0x...",
  "threshold": {
    "type": "percentage",
    "value": 10
  },
  "notification": {
    "webhook": "https://your-server.com/webhook",
    "email": "[email protected]"
  }
}

Monitoring Scenarios

Scenario 1: New Pool Discovery

Goal: Discover newly created trading pools as early as possible
ws.subscribe('pool_created', {
  chain: 'ethereum',
  min_liquidity_usd: 10000
}, async (pool) => {
  // Check token safety
  const risk = await checkTokenRisk(pool.token_address);
  if (risk.score > 60) {
    notify(`New pool found: ${pool.pair_name}, Liquidity: $${pool.liquidity_usd}`);
  }
});

Scenario 2: Rug Pull Warning

Goal: Monitor rug pull risk for held pools
1

Add Monitoring

Add target pool to monitoring list
2

Set Threshold

Set withdrawal threshold (e.g., single > 10%)
3

Receive Alerts

Receive real-time alerts
4

Adjust Position

Adjust position promptly
ws.subscribe('liquidity_remove', {
  pool: '0x...',
  threshold_percentage: 10
}, (event) => {
  alert(`⚠️ Rug pull warning: ${event.percentage}% liquidity removed`);
});

Scenario 3: Arbitrage Opportunity Discovery

Goal: Discover cross-DEX price differences
1

Subscribe Price Feeds

Subscribe to price feeds from multiple DEXs
2

Calculate Spread

Calculate spread percentage
3

Cost Evaluation

Consider Gas and slippage costs
4

Send Alert

Alert when net profit > threshold
// Listen to prices from multiple DEXs
const prices = {};

ws.subscribe('token_price', { 
  token: 'WETH',
  dex: ['uniswap', 'sushiswap', 'curve']
}, (data) => {
  prices[data.dex] = data.price;
  checkArbitrage(prices);
});

function checkArbitrage(prices) {
  const maxPrice = Math.max(...Object.values(prices));
  const minPrice = Math.min(...Object.values(prices));
  const spread = (maxPrice - minPrice) / minPrice;
  
  if (spread > 0.005) {  // 0.5% spread
    notify(`Arbitrage opportunity: ${spread * 100}% spread`);
  }
}

Scenario 4: Liquidation Monitoring

Goal: Monitor lending position health
1

Get Position

Get lending position for target address
2

Calculate Health Factor

Calculate real-time health factor
3

Warning

Warn when health factor < 1.5
4

Urgent Alert

Urgent alert when health factor < 1.2
async function monitorLiquidationRisk(address: string) {
  const position = await getDefiPosition(address, 'aave_v3');
  
  if (position.health_factor < 1.2) {
    urgentAlert(`🚨 Liquidation risk! Health factor: ${position.health_factor}`);
  } else if (position.health_factor < 1.5) {
    warnAlert(`⚠️ Low health factor: ${position.health_factor}`);
  }
}

Data Latency

Data TypeLatencyDescription
Real-time Trades< 3sPushed after block confirmation
TVL Data< 1minMinute-level updates
APY Data< 5minCalculated from recent trades
Holder Data< 1hHourly snapshots

API Endpoints

FunctionEndpoint
Get Protocol TVLGET /v1/defi/{protocol}/tvl
Get Pool InfoGET /v1/defi/{protocol}/pools/{pool_id}
Get User PositionsGET /v1/defi/{protocol}/positions/{address}
Get Yield DataGET /v1/defi/{protocol}/yields