Know your protocol's breaking point before the market does.
DeFiStress is a research-grade framework for comprehensive stress testing and risk analysis of DeFi protocols using Agent-Based Modeling, Monte Carlo simulations, and real on-chain data.
DeFiStress enables rigorous quantitative analysis of DeFi protocol solvency under extreme market conditions. Built on agent-based modeling principles, it simulates realistic market participant behavior to identify systemic risks, optimal parameters, and failure modes.
Hydration Protocol (Polkadot) - Complete stress test using real on-chain data:
- β $128.7M DOT liquidity (verified on-chain)
- β Zero bad debt under 60% crash scenarios
- β 11,840 real user positions analyzed
- β A+ risk rating with comprehensive report
π View Full Report
- Agent-Based Modeling: Simulate 1,000+ market participants (liquidators, borrowers, arbitrageurs, market makers)
- Real Market Data: Fetch live prices (Binance), on-chain data (RPC), and liquidity estimates (CoinGecko)
- On-Chain Integration: Connect to live protocols (Hydration, etc.) via RPC endpoints
- Stress Testing: Model crashes, de-pegging events, liquidity crises
- Monte Carlo Analysis: Run 1,000+ scenarios for statistical confidence
- Risk Quantification: Measure bad debt, insolvency thresholds, liquidation cascades
- Professional Visualization: Publication-quality charts and dashboards
- Pre-launch validation: Test parameters before deployment
- Parameter optimization: Find optimal LTV and liquidation thresholds
- Risk monitoring: Identify vulnerabilities in current configurations
- Systemic risk analysis: Study contagion and cascade effects
- Comparative studies: Benchmark different protocol designs
- Academic publications: Validated methodology for peer-reviewed research
- Solvency assessment: Quantify protocol health under stress
- Scenario planning: Model specific market events
- Governance support: Provide data-driven recommendations
# Clone repository
git clone https://github.com/yourusername/solvency.git
cd solvency
# Install dependencies
julia --project=. -e 'using Pkg; Pkg.instantiate()'# 1. Fetch real on-chain data from Hydration blockchain
cd scripts && node fetch_hydration_data.js && cd ..
# 2. Run stress test analysis with REAL DATA
julia --project=. examples/hydration_analysis.jl
# 3. Generate professional visualizations
julia --project=. visualize_hydration.jlOutput: 5 professional charts + CSV data + Forum post in output/hydration_analysis/
# Basic stress test
julia --project=. examples/01_basic_stress_test.jl
# AMM vs CLOB comparison
julia --project=. examples/02_amm_vs_clob_analysis.jl# Launch Jupyter notebook
julia -e 'using IJulia; notebook(dir="notebooks")'Open DeFi_Risk_Analysis_Tutorial.ipynb for a complete walkthrough.
π Fetching live market data from Binance...
β Live prices fetched:
ETH: $3107.26
BTC: $90189.7
π₯ Crash Scenario: 40% ETH drop
Results:
Total Liquidations: 414
Liquidation Volume: $28.5M
Bad Debt: $0
Protocol LTV: 26.43%
Solvency Ratio: 2.784
β
Protocol remains solvent
6-panel dashboard showing price movements, liquidations, and protocol health
Analysis of liquidation volume vs available liquidity
solvency/
βββ src/julia/ # Core simulation engine (1,500 lines)
β βββ agents/ # Agent definitions and behaviors
β βββ models/ # Protocol and market models
β βββ simulations/ # Stress test engine
β βββ visualization/ # Chart generation (deprecated, use Plots.jl)
βββ src/python/ # Data pipeline (1,000 lines)
β βββ data/ # Market data fetchers
β βββ reports/ # Report generation
βββ examples/ # Ready-to-run analyses
β βββ 01_basic_stress_test.jl
β βββ 02_amm_vs_clob_analysis.jl
βββ notebooks/ # Interactive tutorials
β βββ DeFi_Risk_Analysis_Tutorial.ipynb
βββ test_simulation.jl # Quick validation test
βββ visualize_results.jl # Chart generation script
- Liquidators: Monitor positions, execute profitable liquidations with gas costs and reaction delays
- Arbitrageurs: Exploit price differences with speed advantages
- Market Makers: Provide liquidity with inventory risk management
- Borrowers: Take leveraged positions with varying risk tolerances
- Geometric Brownian Motion: Normal market volatility
- Crash Scenarios: Exponential decay with recovery
- Correlated Assets: Multi-asset price movements
- De-pegging Events: Stablecoin failures
- Dynamic Liquidity: Volatility-dependent depth
- Lending Protocols: Aave/Compound-style with health factors
- AMM: Constant product (Uniswap-style)
- CLOB: Order book-based exchanges
The framework has been validated against historical events:
- March 2020 "Black Thursday": ETH crash and MakerDAO liquidations
- May 2021 Flash Crash: Multi-asset cascade
- November 2022 FTX Collapse: Contagion effects
Typical accuracy: Β±15% on bad debt estimates
- Liquidators act rationally to maximize profit
- Gas costs average $50 per liquidation
- Oracle delays of 1-2 blocks
- Market makers reduce liquidity 50-70% during high volatility
- No external liquidity sources (CEX arbitrage not modeled)
protocol = ProtocolParams(
"My Protocol",
["ETH", "WBTC", "USDC"],
Dict("ETH" => 0.80, "WBTC" => 0.75, "USDC" => 0.90), # LTV ratios
Dict("ETH" => 0.85, "WBTC" => 0.80, "USDC" => 0.95"), # Liquidation thresholds
0.10, # 10% liquidation penalty
2, # Oracle delay (blocks)
100.0 # Minimum collateral
)mc_results = run_monte_carlo_stress_test(
config,
protocol,
1000, # Number of simulations
crash_magnitudes = [0.2, 0.3, 0.4, 0.5]
)ltv_values = 0.65:0.05:0.85
results = []
for ltv in ltv_values
protocol.ltv_ratios["ETH"] = ltv
result = run_stress_test(config, protocol, prices, liquidity)
push!(results, result["total_bad_debt"])
end- Single Scenario: 2-5 seconds (500 borrowers, 300 blocks)
- Monte Carlo (1000 runs): 30-60 minutes
- Memory: ~2GB for large simulations
Optimizations:
- Reduce
n_borrowersfor faster iteration - Use fewer
n_blocksfor parameter sweeps - Parallelize Monte Carlo with
Distributed.jl
- README.md (this file): Project overview
- CONTRIBUTING.md: Contribution guidelines
- docs/USAGE_GUIDE.md: Comprehensive technical guide
- notebooks/: Interactive tutorials
If you use this framework in academic research, please cite:
@software{solvency2024,
title={Solvency: DeFi Protocol Risk Analysis Framework},
author={[Your Name]},
year={2024},
url={https://github.com/yourusername/solvency},
version={0.1.0}
}We welcome contributions! See CONTRIBUTING.md for guidelines.
High-priority areas:
- Additional protocol models (Curve, Balancer, GMX)
- Historical event replay
- Multi-chain support
- Enhanced agent behaviors
MIT License - See LICENSE for details.
- Inspired by Gauntlet and Chaos Labs methodologies
- Built with Agents.jl and Plots.jl
- Market data from Binance API
This framework is for research and analysis purposes. Results are probabilistic models, not guarantees. Always validate findings with additional analysis and testing before making protocol decisions.
Made for rigorous DeFi risk analysis. Not financial advice.