Liquidation Cascades: How AI Agents Monitor, Predict, and Profit from Mass Liquidations
Liquidation cascades are among the most violent and predictable events in crypto markets. A single price move triggers forced sells, which push prices lower, which triggers more liquidations, which push prices lower still — a self-reinforcing spiral that can erase 30% of an asset's value in minutes. For AI agents with the right infrastructure, these events are not disasters; they are calendared opportunities. This post covers what triggers cascades, how to detect them on-chain before they detonate, and how to implement a full cascade monitoring agent using Purple Flea's trading API across 275 perpetual markets.
What Is a Liquidation Cascade?
In leveraged markets — perpetual futures, margin lending protocols, and CDP vaults — every position has a health factor or maintenance margin threshold. When collateral value falls below that threshold, the position is forcibly closed (liquidated). The liquidation itself sells the underlying asset, which depresses the price further, pushing other leveraged positions closer to their own thresholds. This creates a cascade.
In DeFi, the cascade is visible on-chain in real time: you can see every vault's collateral ratio, every protocol's liquidation queue, and every margin call before it triggers. This transparency, absent in traditional finance, is what makes cascade hunting tractable for autonomous agents.
Anatomy of a Cascade
Phase 1: The Trigger
Cascades start with a liquidity event that moves the market against the crowd's position. Common triggers include:
- Macro news shocks — Fed rate decisions, CPI prints, geopolitical events causing rapid dollar strengthening
- Protocol exploits — A hack or rug drains collateral, triggering immediate mass liquidations
- Whale exits — A single large sell order exhausts order book depth and prints a large candle
- Oracle manipulation — Flash loan attacks that temporarily move price feeds to trigger artificial liquidations
- Funding rate extremes — When perpetual funding rates become unsustainable, positions unwind simultaneously
Phase 2: First Wave Liquidations
The initial price move crosses the liquidation threshold of the most leveraged positions — typically those at 25x-100x leverage. These positions are sold by the protocol's liquidation engine, often as market orders into thin liquidity. The resulting slippage amplifies the price drop.
Phase 3: Cascade Propagation
Lower prices hit the next tier of leveraged positions — 10x-25x leverage. Their liquidations further depress prices. On centralized exchanges, this manifests as a "liquidation ladder" visible in the order book data. On DeFi protocols, you can watch health factors tick down in real time via RPC calls.
Phase 4: Forced Bounce or Extended Collapse
Either panic capitulation creates a V-shaped recovery (buyers absorb forced sells at a discount), or the cascade exhausts all bid liquidity and the price continues lower until a new equilibrium forms. The depth of the cascade depends on: total open interest at risk, available liquidation bot competition, and whether market makers step back from quoting.
On-Chain Liquidation Data Sources
Unlike traditional markets where liquidation data is hidden, DeFi protocols broadcast every liquidation event on-chain. Here are the primary data sources agents should monitor:
| Protocol | Chain | Liquidation Event | RPC Method |
|---|---|---|---|
| Aave v3 | ETH/ARB/OP | LiquidationCall | eth_getLogs |
| Compound v3 | ETH/BASE | AbsorbDebt | eth_getLogs |
| MakerDAO | ETH | Clip.Take | eth_getLogs |
| dYdX v4 | Cosmos | Liquidation order type | WebSocket stream |
| Hyperliquid | L1 | Liquidation fills in trade stream | WebSocket wss://api.hyperliquid.xyz/ws |
| GMX v2 | ARB | LiquidationOrder | eth_getLogs |
| Synthetix Perps | OP/BASE | PositionLiquidated | eth_getLogs |
Beyond protocol-level events, agents should also monitor cross-protocol aggregate feeds like Parsec Finance, DeBank, and Chaos Labs — these provide pre-aggregated at-risk position data that saves RPC calls.
Health Factor Monitoring
The key metric for predicting an impending cascade is the aggregate health factor distribution across a protocol. Aave defines health factor as:
HF = (Σ collateral_i × liquidation_threshold_i) / total_debt_in_base_currency
When HF drops below 1.0, the position is liquidatable. An agent monitoring the distribution of health factors across all positions can estimate:
- How much price drop is needed to trigger the first wave (positions with HF between 1.0 and 1.05)
- How much additional selling would result from first-wave liquidations
- The total cascade depth if the spiral propagates through multiple tiers
A 5% drop in ETH price that puts $2B of positions into liquidation territory generates approximately $200-400M in forced selling (depending on leverage levels), which itself can cause an additional 2-4% price drop — triggering the next wave.
Aave Health Factor Polling
// Aave v3 health factor via RPC
const { ethers } = require('ethers');
const AAVE_POOL = '0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2';
const ABI = [
'function getUserAccountData(address user) view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)'
];
async function getHealthFactor(userAddress, provider) {
const pool = new ethers.Contract(AAVE_POOL, ABI, provider);
const data = await pool.getUserAccountData(userAddress);
const hf = parseFloat(ethers.formatUnits(data.healthFactor, 18));
return hf;
}
// At-risk positions: HF between 1.0 and 1.1
// Imminent liquidation: HF between 1.0 and 1.02
Cascade Prediction Signals
A complete cascade prediction system combines on-chain position data with market microstructure signals. Here are the highest-signal indicators:
Signal 1: Open Interest Concentration
When open interest on perpetual futures is highly concentrated on one side (e.g., 70%+ long), the market is fragile. A move against the crowd will trigger outsized liquidations. Monitor the long/short ratio across all Purple Flea's 275 perp markets continuously.
Signal 2: Funding Rate Extremes
Funding rates above 0.1% per 8 hours (annualized: >109%) indicate extreme long positioning. Shorts are being paid to hold, which means the market is at peak greed — and highly susceptible to a cascade. Conversely, deeply negative funding signals a potential short squeeze cascade.
Signal 3: Liquidation Map Density
Exchanges and analysis tools publish "liquidation heatmaps" — price levels where large clusters of leveraged positions will be force-closed. When a cluster of $500M+ in liquidations sits within 3% of current price, cascade risk is elevated.
Signal 4: Order Book Thinning
Cascades accelerate when market makers pull liquidity. Monitor the bid-ask spread and order book depth at 1%, 2%, and 5% from mid. A sudden 3x increase in spread or 50% reduction in depth predicts imminent volatility.
Signal 5: Cross-Exchange Premium Divergence
When the perpetual price on one exchange diverges significantly from spot or other perp venues, it signals either an impending cascade (perp trading at large discount = forced liquidations incoming) or a short squeeze (perp at large premium).
No single signal is sufficient. Cascades can be interrupted by large buyers absorbing the selling. Always use multiple confirming signals and implement strict position sizing. A cascade prediction model with 60% accuracy is highly profitable but requires robust risk management for the 40% false positives.
Agent Strategies: Hunting vs. Protection
Strategy A: Cascade Hunting
Cascade hunting agents take short positions immediately before or during a cascade, profiting from the forced selling. The edge comes from being faster than the crowd to identify the signal.
Implementation steps:
- Monitor all cascade signals in real time (OI concentration, funding rate, liquidation map density, order book depth)
- Compute a composite "cascade risk score" for each major asset
- When the score exceeds a threshold, open a short position on Purple Flea perps with predefined size (e.g., 2% of portfolio)
- Set a take-profit at the estimated cascade terminus (liquidation cluster bottom)
- Set a tight stop-loss above entry (cascade doesn't materialize)
- Close the position as liquidation volume spikes begin to slow (cascade exhaust signal)
Strategy B: Position Protection
Protection agents monitor existing long positions against cascade risk and act defensively:
- Dynamic deleveraging — Reduce position size as cascade risk score rises
- Cascade hedges — Open offsetting short positions on correlated assets when risk is elevated
- Collateral management — Add collateral to DeFi lending positions to raise health factor before liquidation
- Liquidation racing — Self-liquidate at market price before the protocol's forced liquidation incurs additional penalty fees
Strategy C: Liquidation Bots
On-chain liquidation bots perform the actual forced closes on DeFi protocols, earning a liquidation bonus (typically 5-8% of the liquidated collateral). These bots need:
- High-speed RPC nodes (Alchemy, Infura, or self-hosted)
- Pre-funded accounts to execute liquidations atomically
- MEV (maximal extractable value) protections to avoid being frontrun by other bots
- Flash loan access to liquidate without capital requirements
Liquidation bots operate in an extremely competitive MEV environment. Without block builder relationships or private mempools (Flashbots), your liquidation transactions will be frontrun by other bots. This is an area where agent speed and infrastructure quality directly determine profitability.
Purple Flea Trading API for Cascade Trades
Purple Flea provides access to 275 perpetual markets via the Hyperliquid integration, giving agents the ideal venue for executing cascade strategies. All positions are fully on-chain with transparent liquidation mechanics.
API Setup
// Register and get API credentials
const BASE_URL = 'https://purpleflea.com/api/v1';
async function registerAgent() {
const res = await fetch(`${BASE_URL}/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'cascade-hunter-v1',
email: 'agent@example.com'
})
});
const { apiKey, agentId } = await res.json();
return { apiKey, agentId };
}
// Place a short on ETH perp
async function openShort(apiKey, asset, sizeDollars, leverage) {
const res = await fetch(`${BASE_URL}/trading/order`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
asset,
direction: 'short',
size_usd: sizeDollars,
leverage,
order_type: 'market',
reduce_only: false
})
});
return res.json();
}
Kill Switch Implementation
Every cascade-hunting agent must have a kill switch — an automated circuit breaker that closes all positions and halts trading when losses exceed a threshold or when market conditions become unmodeled. This is non-negotiable.
class CascadeKillSwitch {
constructor(apiKey, maxDrawdownPct = 5) {
this.apiKey = apiKey;
this.maxDrawdown = maxDrawdownPct / 100;
this.startingEquity = null;
this.active = true;
}
async checkAndAct(currentEquity) {
if (!this.startingEquity) this.startingEquity = currentEquity;
const drawdown = (this.startingEquity - currentEquity) / this.startingEquity;
if (drawdown >= this.maxDrawdown && this.active) {
console.log(`[KILL SWITCH] Drawdown ${(drawdown*100).toFixed(2)}% exceeds limit. Closing all positions.`);
this.active = false;
await this.closeAllPositions();
}
}
async closeAllPositions() {
const res = await fetch(`${BASE_URL}/trading/positions`, {
headers: { 'Authorization': `Bearer ${this.apiKey}` }
});
const positions = await res.json();
for (const pos of positions) {
await fetch(`${BASE_URL}/trading/order`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
body: JSON.stringify({
asset: pos.asset,
direction: pos.direction === 'long' ? 'short' : 'long',
size_usd: pos.size_usd,
order_type: 'market',
reduce_only: true
})
});
}
}
}
Full Python Cascade Monitor Implementation
Below is a complete Python implementation of a cascade monitoring agent. It polls on-chain data, computes the cascade risk score, and executes trades via the Purple Flea API when thresholds are crossed.
#!/usr/bin/env python3
"""
Purple Flea Cascade Monitor Agent
Monitors liquidation risk across DeFi protocols and perp markets,
executes short positions when cascade probability is high.
"""
import asyncio
import aiohttp
import json
import time
from dataclasses import dataclass, field
from typing import Optional
PURPLE_FLEA_BASE = "https://purpleflea.com/api/v1"
HYPERLIQUID_WS = "wss://api.hyperliquid.xyz/ws"
AAVE_SUBGRAPH = "https://api.thegraph.com/subgraphs/name/aave/protocol-v3"
@dataclass
class CascadeSignal:
asset: str
oi_long_ratio: float # 0-1, fraction of OI that is long
funding_rate_8h: float # annualized equivalent
liquidation_density: float # USD at risk within 3% of current price
orderbook_depth_pct: float # depth relative to 7-day average
risk_score: float = field(init=False)
def __post_init__(self):
self.risk_score = self._compute_risk_score()
def _compute_risk_score(self) -> float:
"""Compute composite cascade risk score (0-100)."""
score = 0.0
# OI concentration: 50%+ long = rising risk
if self.oi_long_ratio > 0.65:
score += (self.oi_long_ratio - 0.65) / 0.35 * 30
# Extreme funding
if self.funding_rate_8h > 0.05: # >5% annualized
score += min(self.funding_rate_8h / 0.15, 1.0) * 25
# Liquidation density
if self.liquidation_density > 200_000_000: # $200M
score += min(self.liquidation_density / 1_000_000_000, 1.0) * 30
# Order book thinning
if self.orderbook_depth_pct < 0.7:
score += (0.7 - self.orderbook_depth_pct) / 0.7 * 15
return min(score, 100.0)
class CascadeMonitor:
def __init__(self, api_key: str, max_position_usd: float = 10_000):
self.api_key = api_key
self.max_position_usd = max_position_usd
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
self.active_positions: dict = {}
self.equity_start: Optional[float] = None
async def get_perp_data(self, session: aiohttp.ClientSession, asset: str) -> dict:
"""Fetch open interest and funding from Purple Flea / Hyperliquid."""
url = f"{PURPLE_FLEA_BASE}/trading/markets/{asset}"
async with session.get(url, headers=self.headers) as resp:
return await resp.json()
async def get_aave_at_risk(self, session: aiohttp.ClientSession,
asset: str, price_drop_pct: float = 0.03) -> float:
"""Query Aave subgraph for USD at risk given a price drop."""
query = """
{
reserves(where: {symbol: "%s"}) {
userReserves(where: {usageAsCollateralEnabledOnUser: true}) {
user { id }
currentATokenBalance
}
}
}
""" % asset
# Simplified: return cached estimate in production
# Full implementation would sum positions with HF < 1 + price_drop_pct buffer
return 0.0 # placeholder
def compute_signal(self, market_data: dict, asset: str) -> CascadeSignal:
oi_long = market_data.get("oi_long_ratio", 0.5)
funding = market_data.get("funding_rate_8h", 0.01)
liq_density = market_data.get("liquidation_density_usd", 0)
depth_pct = market_data.get("orderbook_depth_ratio", 1.0)
return CascadeSignal(
asset=asset,
oi_long_ratio=oi_long,
funding_rate_8h=funding,
liquidation_density=liq_density,
orderbook_depth_pct=depth_pct
)
async def open_short(self, session: aiohttp.ClientSession,
asset: str, size_usd: float, leverage: int = 3):
"""Open a short position on Purple Flea."""
payload = {
"asset": asset,
"direction": "short",
"size_usd": size_usd,
"leverage": leverage,
"order_type": "market",
"reduce_only": False
}
async with session.post(
f"{PURPLE_FLEA_BASE}/trading/order",
headers=self.headers,
json=payload
) as resp:
result = await resp.json()
if result.get("status") == "filled":
self.active_positions[asset] = {
"size_usd": size_usd,
"entry_price": result["fill_price"],
"opened_at": time.time()
}
print(f"[TRADE] Opened short {asset} ${size_usd:,.0f} @ {result['fill_price']}")
return result
async def check_kill_switch(self, session: aiohttp.ClientSession):
"""Check drawdown and close all if exceeded."""
async with session.get(
f"{PURPLE_FLEA_BASE}/account/equity",
headers=self.headers
) as resp:
data = await resp.json()
equity = data.get("equity_usd", 0)
if self.equity_start is None:
self.equity_start = equity
return
drawdown = (self.equity_start - equity) / self.equity_start
if drawdown > 0.05: # 5% max drawdown
print(f"[KILL SWITCH] Drawdown {drawdown:.1%} — closing all positions")
for asset in list(self.active_positions.keys()):
await self.close_position(session, asset)
async def close_position(self, session: aiohttp.ClientSession, asset: str):
"""Close an open short position."""
pos = self.active_positions.get(asset)
if not pos:
return
payload = {
"asset": asset,
"direction": "long", # buy to close short
"size_usd": pos["size_usd"],
"order_type": "market",
"reduce_only": True
}
async with session.post(
f"{PURPLE_FLEA_BASE}/trading/order",
headers=self.headers,
json=payload
) as resp:
result = await resp.json()
del self.active_positions[asset]
print(f"[TRADE] Closed short {asset} @ {result.get('fill_price')}")
async def run(self, assets: list[str], poll_interval: int = 30):
"""Main monitoring loop."""
RISK_THRESHOLD = 65.0 # trigger short above this score
print(f"[MONITOR] Starting cascade monitor for {assets}")
async with aiohttp.ClientSession() as session:
while True:
await self.check_kill_switch(session)
for asset in assets:
try:
market_data = await self.get_perp_data(session, asset)
signal = self.compute_signal(market_data, asset)
print(f"[{asset}] risk_score={signal.risk_score:.1f} "
f"oi_long={signal.oi_long_ratio:.0%} "
f"funding={signal.funding_rate_8h:.2%}")
if signal.risk_score >= RISK_THRESHOLD and asset not in self.active_positions:
size = self.max_position_usd * (signal.risk_score / 100) * 0.5
await self.open_short(session, asset, size_usd=size, leverage=3)
elif signal.risk_score < 40 and asset in self.active_positions:
# Risk resolved — close position
await self.close_position(session, asset)
except Exception as e:
print(f"[ERROR] {asset}: {e}")
await asyncio.sleep(poll_interval)
async def main():
# Register agent via faucet for free starting capital
# https://faucet.purpleflea.com
api_key = "YOUR_PURPLE_FLEA_API_KEY"
monitor = CascadeMonitor(api_key=api_key, max_position_usd=5_000)
watch_assets = ["ETH", "BTC", "SOL", "ARB", "OP", "AVAX", "LINK"]
await monitor.run(watch_assets, poll_interval=30)
if __name__ == "__main__":
asyncio.run(main())
Risk Management for Cascade Strategies
Cascade trading carries unique risks that standard portfolio management frameworks underestimate:
Countertrend Risk
The market does not always cascade even when signals are elevated. Large buyers (institutions, protocol treasuries, exchanges liquidating their own hedge books) may absorb the selling entirely. Your short position then loses money during a "cascade that didn't happen." Size positions at 1-3% of portfolio per trade.
Slippage and Execution Risk
During actual cascades, order book liquidity evaporates. If you're entering at the start of a cascade, you may get filled at a worse price than expected. If closing, you may be competing with liquidation bots and panic sellers. Use limit orders with urgency pricing rather than pure market orders.
Correlation Collapse
During cascades, all crypto assets become highly correlated. A hedge in BTC does not protect against an ETH cascade if both move -15% simultaneously. Use diversified hedges and maintain enough cash/stables to survive multi-asset simultaneous cascades.
Backtest your cascade signals against at least 5 major historical cascade events (May 2021, November 2022, March 2020, June 2022, August 2024). If your model would have been profitable in at least 4 of 5, with drawdowns below 10%, it is ready for paper trading. Only then go live with small capital.
Edge Cases and Protocol-Specific Nuances
- Oracle latency: Some DeFi protocols update price feeds every few minutes. During a fast cascade, the protocol price may lag spot by 2-5%, meaning liquidations happen later than on-chain health factors suggest.
- Liquidation incentive caps: Aave caps the liquidation bonus at 15% and limits what fraction of a position can be liquidated in one transaction. Large positions may require multiple liquidation transactions.
- Insurance funds: Centralized exchanges and some DeFi protocols maintain insurance funds that absorb losses before socialized losses hit other traders. Monitor insurance fund depletion as an additional cascade risk signal.
- Perpetual settlement: When cascades push perpetual funding rates to extreme negative values, longs start being paid to hold their positions — this can slow or stop a cascade as new longs enter to collect funding.
- Hyperliquid-specific: Hyperliquid uses a fully on-chain order book with instant finality. Liquidations are visible in the trade feed with a
"liq": trueflag. Monitor this flag to count liquidation rate in real time.
Getting Started on Purple Flea
Purple Flea provides everything an autonomous cascade-hunting agent needs in one platform:
- Faucet — faucet.purpleflea.com: Claim free capital to bootstrap your agent
- Trading — 275 perpetual markets via Hyperliquid, full REST and WebSocket API
- Wallet — Multi-chain custody for collateral management across ETH, BTC, SOL, TRX, BNB, MATIC
- Escrow — escrow.purpleflea.com: Trustless agent-to-agent payments for strategy subscriptions and signal sharing
- MCP tools — Both faucet and escrow expose MCP endpoints for LLM-native agents
Liquidation cascades are predictable, measurable, and tradeable. An agent with the right on-chain data sources, a well-calibrated risk score, and disciplined position sizing can generate consistent alpha during these high-volatility events. The Python implementation above gives you a starting framework. Customize the signal weights to your target assets, backtest against historical data, and deploy via Purple Flea's trading API. Register your agent at purpleflea.com/register.