2 releases
Uses new Rust 2024
| 0.1.1-alpha.3 | Dec 8, 2025 |
|---|
#7 in #liquidity-provider
755KB
17K
SLoC
Crates
| Crate | Version | Docs |
|---|---|---|
clmm-lp-domain |
||
clmm-lp-simulation |
||
clmm-lp-optimization |
||
clmm-lp-protocols |
||
clmm-lp-execution |
||
clmm-lp-data |
||
clmm-lp-cli |
||
clmm-lp-api |
CLMM Liquidity Provider Strategy Optimizer - Solana
A powerful, production-ready strategy optimization and execution engine for liquidity providers on Solana Concentrated Liquidity Market Makers (CLMMs). This project supports Orca Whirlpools, Raydium CLMM, and Meteora DLMM.
Built for market makers and sophisticated LPs who need to:
- Analyze pools and calculate impermanent loss (IL) in real-time
- Simulate positions over historical data with multiple rebalancing strategies
- Execute automated rebalancing based on volatility, volume, and asset correlation
- Monitor positions with real-time alerts and notifications
- Access everything via CLI, REST API, or Web Dashboard
π Value Proposition
DeFi market making requires more than just chasing high APY. This project solves three critical problems:
- Risk Quantification: Precise calculation of impermanent loss risks before entering positions.
- Range Optimization: Finding the mathematical optimal tick ranges to maximize fee capture while minimizing IL.
- Scenario Simulation: Stress-testing positions against historical and Monte Carlo simulated market conditions.
π Architecture
The project follows a Domain-Driven Design (DDD) approach, separated into modular crates within a cargo workspace.
graph TD
subgraph "User Interfaces"
User[User]
Browser[Web Browser]
end
User --> CLI[CLI Crate]
User --> API[API Crate]
Browser --> Dashboard[Web Dashboard]
Dashboard --> API
subgraph "Application Layer"
CLI --> Optimization[Optimization Crate]
CLI --> Simulation[Simulation Crate]
API --> Execution[Execution Crate]
API --> Protocols[Protocols Crate]
end
subgraph "Core Domain"
Optimization --> Domain[Domain Crate]
Simulation --> Domain
Execution --> Domain
Protocols --> Domain
end
subgraph "Infrastructure"
Simulation --> Data[Data Crate]
Execution --> Protocols
Protocols --> Data
Data --> DB[(PostgreSQL)]
end
subgraph "External Services"
Protocols -.-> |RPC| Solana[Solana Blockchain]
Data -.-> |HTTP| Birdeye[Birdeye API]
Data -.-> |HTTP| Jupiter[Jupiter API]
API -.-> |WebSocket| Clients[WS Clients]
end
Module Overview
| Crate | Description |
|---|---|
clmm-lp-domain |
Core entities, value objects, CLMM math, tick calculations, and IL formulas |
clmm-lp-simulation |
Backtesting engine, price path generators, rebalancing strategies |
clmm-lp-optimization |
Strategy optimization with Grid Search, objective functions (PnL, Sharpe, IL) |
clmm-lp-protocols |
Solana protocol adapters (Orca Whirlpools), RPC provider with failover |
clmm-lp-execution |
Live monitoring, PnL tracking, alerts, wallet management, strategy execution |
clmm-lp-data |
Data providers (Birdeye, Jupiter), caching, PostgreSQL repositories |
clmm-lp-cli |
CLI with analyze, backtest, optimize, monitor commands. Multiple output formats |
clmm-lp-api |
REST API with Swagger UI, JWT auth, WebSocket support |
Web Dashboard
| Component | Description |
|---|---|
| Dashboard | Portfolio overview with charts and metrics |
| Positions | Position management with real-time updates |
| Strategies | Strategy configuration and control |
| Pools | Pool explorer with TVL, volume, APY |
| Settings | Configuration and preferences |
π Tech Stack
Backend (Rust)
| Category | Technology |
|---|---|
| Language | Rust 1.90+ (Edition 2024) |
| Async Runtime | Tokio |
| Web Framework | Axum |
| Database | PostgreSQL (SQLx) |
| Blockchain | solana-sdk, solana-client |
| Math | rust_decimal, fixed-point precision |
| Serialization | Serde, JSON |
| Logging | tracing with structured logs |
| Testing | proptest for property-based testing |
| API Docs | utoipa (OpenAPI/Swagger) |
Frontend (TypeScript)
| Category | Technology |
|---|---|
| Framework | React 18 |
| Build Tool | Vite |
| Styling | TailwindCSS |
| State Management | React Query (TanStack) |
| Routing | React Router |
| Charts | Recharts |
| Icons | Lucide React |
π Roadmap & Status
The project is being built in incremental phases. Current version: 0.1.1-alpha.2
| Phase | Name | Status | Progress |
|---|---|---|---|
| 0 | Foundation | β Complete | 100% |
| 1 | Core Domain Models | β Complete | 100% |
| 2 | Simulation Engine | β Complete | 100% |
| 3 | Data Integration | β Complete | 100% |
| 4 | Optimization Engine | β Complete | 100% |
| 5 | CLI & Reporting | β Complete | 100% |
| 6 | Database & Persistence | β Complete | 100% |
| 7 | Blockchain Integration | β Complete | 100% |
| 8 | Live Monitoring | β Complete | 100% |
| 9 | Transaction Execution | β Complete | 100% |
| 10 | Strategy Automation | β Complete | 100% |
| 11 | REST API | β Complete | 100% |
| 12 | Web Dashboard | β Complete | 100% |
| 13 | Production Hardening | β Complete | 100% |
| 14 | Advanced Features | οΏ½ Planned | 0% |
Overall Progress: ~100% (Phases 0-13 complete, Phase 14 planned for future)
β¨ Features
Core Capabilities
- CLMM Mathematics: Full implementation of concentrated liquidity math (tick β price, sqrt_price, liquidity calculations)
- Impermanent Loss: Precise IL calculation for concentrated positions with range boundaries
- Backtesting: Simulate LP positions against historical price data with multiple rebalancing strategies
- Optimization: Find optimal tick ranges using Grid Search with configurable objective functions
- Multi-Protocol: Support for Orca Whirlpools, Raydium CLMM (Meteora DLMM planned)
Rebalancing Strategies
| Strategy | Description |
|---|---|
| Static | Hold position without rebalancing |
| Periodic | Rebalance at fixed time intervals |
| Threshold | Rebalance when price moves beyond threshold |
| IL Limit | Rebalance when impermanent loss exceeds limit |
Optimization Objectives
- Maximize Net PnL - Total return after fees and IL
- Maximize Fee Earnings - Focus on fee capture
- Maximize Sharpe Ratio - Risk-adjusted returns
- Minimize IL - Conservative IL minimization
- Maximize Time in Range - Optimize for range efficiency
Live Monitoring
- Position Tracking: Real-time position state from on-chain
- PnL Calculation: Entry value, current value, fees, IL, net PnL, APY
- Alert System: Configurable rules for range exit, IL thresholds, PnL targets
- Multi-Channel Notifications: Console, file, webhook
REST API
- OpenAPI/Swagger: Full API documentation at
/docs - JWT Authentication: Secure API access with role-based permissions
- API Key Support: Alternative authentication method
- WebSocket: Real-time position updates and alerts
Web Dashboard
- Portfolio Overview: Total value, PnL, fees, impermanent loss
- Position Management: View, rebalance, collect fees, close positions
- Strategy Control: Create, configure, start/stop automated strategies
- Pool Explorer: Browse pools with TVL, volume, and APY metrics
- Real-time Updates: WebSocket integration for live data
β‘οΈ Quick Start
Prerequisites
- Rust: 1.90+ (edition 2024)
- Node.js: 18+ (for web dashboard)
- Make: Build automation
- Docker: Optional, for PostgreSQL
- PostgreSQL: 14+ (optional, for persistence)
Installation
# Clone the repository
git clone https://github.com/joaquinbejar/CLMM-Liquidity-Provider.git
cd CLMM-Liquidity-Provider
# Build the project
make build
# Run tests
make test
# Install CLI globally (optional)
cargo install --path crates/cli
Common Commands
The project includes a comprehensive Makefile for common tasks:
# Build the project
make build
# Run all tests (Unit & Integration)
make test
# Format code
make fmt
# Run Clippy lints
make lint
# Fix linting issues automatically
make lint-fix
# Pre-push checks (format + lint + test)
make pre-push
# Generate Documentation
make doc-open
Running the API Server
# Start the API server (default port 8080)
cargo run --bin clmm-lp-api
# Or with environment variables
RUST_LOG=info API_PORT=8080 cargo run --bin clmm-lp-api
The API will be available at:
- REST API:
http://localhost:8080/api/v1 - Swagger UI:
http://localhost:8080/docs - WebSocket:
ws://localhost:8080/ws
Running the Web Dashboard
# Navigate to web directory
cd web
# Install dependencies
npm install
# Start development server
npm run dev
The dashboard will be available at http://localhost:3000.
Note: The web dashboard requires the API server to be running on port 8080.
CLI Usage
# Analyze a trading pair
clmm-lp-cli analyze --symbol-a SOL --symbol-b USDC --days 30
# Run a backtest with periodic rebalancing
clmm-lp-cli backtest --symbol-a SOL --symbol-b USDC \
--capital 10000 --lower-price 80 --upper-price 120 \
--strategy periodic --rebalance-interval 24
# Optimize range parameters
clmm-lp-cli optimize --symbol-a SOL --symbol-b USDC \
--capital 10000 --objective sharpe
# Fetch and cache market data
clmm-lp-cli data fetch --symbol SOL --days 90
# Monitor a live position
clmm-lp-cli monitor --position <POSITION_ADDRESS> --interval 30
Output Formats
The CLI supports multiple output formats:
- Table: Rich formatted tables (default)
- JSON: Machine-readable JSON output
- CSV: Spreadsheet-compatible export
- HTML: Web-ready reports
- Markdown: Documentation-friendly format
π Project Structure
CLMM-Liquidity-Provider/
βββ Cargo.toml # Workspace configuration
βββ Makefile # Task runner
βββ .env.example # Environment variables template
βββ crates/
β βββ api/ # REST API (Axum)
β β βββ handlers/ # Request handlers
β β βββ models.rs # API request/response models
β β βββ auth.rs # JWT & API key authentication
β β βββ openapi.rs # Swagger/OpenAPI documentation
β β βββ websocket.rs # WebSocket handlers
β βββ cli/ # CLI application
β β βββ commands/ # analyze, backtest, optimize, data, monitor
β β βββ output/ # table, chart, export modules
β βββ data/ # Data layer
β β βββ providers/ # Birdeye, Jupiter API clients
β β βββ repositories/ # PostgreSQL repositories
β β βββ cache/ # In-memory and file caching
β β βββ migrations/ # SQL migration files
β βββ domain/ # Core business logic
β β βββ entities/ # Pool, Position, Token
β β βββ metrics/ # IL, fees, PnL calculations
β β βββ math/ # Tick math, liquidity, sqrt_price
β βββ execution/ # Live execution engine
β β βββ alerts/ # Alert rules and notifiers
β β βββ monitor/ # Position monitor, PnL tracker
β β βββ strategy/ # Decision engine, executor
β β βββ transaction/ # Builder, manager
β β βββ wallet/ # Wallet management
β βββ optimization/ # Strategy optimization
β β βββ grid_search.rs # Grid search optimizer
β β βββ objectives.rs # Objective functions
β βββ protocols/ # Blockchain adapters
β β βββ orca/ # Whirlpool reader, executor
β β βββ rpc/ # RPC provider with failover
β β βββ events/ # Event fetcher and parser
β βββ simulation/ # Backtesting engine
β βββ models/ # Price path, volume, liquidity
β βββ strategies/ # Static, Periodic, Threshold, IL Limit
βββ web/ # Web Dashboard (React)
β βββ src/
β β βββ components/ # UI components
β β βββ pages/ # Page components
β β βββ lib/ # API client, utilities
β β βββ hooks/ # React hooks
β βββ package.json
β βββ vite.config.ts
βββ Docker/ # Docker deployment
β βββ docker-compose.yml # Docker Swarm configuration
β βββ api.Dockerfile # API server image
β βββ cli.Dockerfile # CLI tool image
β βββ web.Dockerfile # Web dashboard image
β βββ nginx.conf # Nginx reverse proxy
β βββ monitoring/ # Prometheus, Grafana, AlertManager
βββ tests/
β βββ load/k6/ # Load testing scripts
βββ doc/ # Documentation
βββ steps.md # Implementation roadmap
βββ resume.md # Project overview
βββ PROGRESS.md # Development progress tracker
βββ BACKUP_DISASTER_RECOVERY.md # DR procedures
π§ͺ Testing Strategy
We employ a rigorous testing strategy to ensure financial safety:
- Unit Tests: For all mathematical formulas (Tick Math, IL)
- Property-Based Tests: To verify invariants (e.g., "Liquidity can never be negative")
- Integration Tests: Mocked RPC calls to verify protocol adapters
- Simulation Tests: Monte Carlo runs to stress-test strategies
- End-to-End Tests: Full workflow testing with test fixtures
# Run all tests
make test
# Run with coverage
make coverage
# Run specific crate tests
cargo test -p clmm-lp-domain
cargo test -p clmm-lp-simulation
π§ Configuration
Environment Variables
Create a .env file based on .env.example:
# Solana RPC
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
SOLANA_RPC_BACKUP_URL=https://solana-api.projectserum.com
# Database (optional)
DATABASE_URL=postgres://user:pass@localhost:5432/clmm_lp
# API Configuration
API_HOST=0.0.0.0
API_PORT=8080
JWT_SECRET=your-secret-key-change-in-production
# Data Providers
BIRDEYE_API_KEY=your-birdeye-api-key
JUPITER_API_URL=https://price.jup.ag/v4
# Logging
RUST_LOG=info,clmm_lp=debug
Strategy Configuration
Strategies can be configured via JSON files:
{
"name": "SOL-USDC Rebalancer",
"strategy_type": "threshold",
"pool_address": "HJPjoWUrhoZzkNfRpHuieeFk9WcZWjwy6PBjZ81ngndJ",
"parameters": {
"rebalance_threshold_pct": 5.0,
"max_il_pct": 2.0,
"min_rebalance_interval_hours": 4,
"range_width_pct": 10.0
}
}
π Security Considerations
- Dry Run Mode: Always test strategies in dry-run mode before live execution
- API Keys: Never commit API keys or secrets to version control
- Wallet Security: Use hardware wallets or secure key management for production
- Rate Limiting: Built-in rate limiting for RPC and API calls
- Circuit Breaker: Automatic strategy pause on excessive losses
π API Endpoints
Health & Metrics
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/health |
Health check |
| GET | /api/v1/metrics |
System metrics |
Positions
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/positions |
List all positions |
| GET | /api/v1/positions/:address |
Get position details |
| POST | /api/v1/positions |
Open new position |
| DELETE | /api/v1/positions/:address |
Close position |
| POST | /api/v1/positions/:address/rebalance |
Rebalance position |
| POST | /api/v1/positions/:address/collect |
Collect fees |
Strategies
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/strategies |
List all strategies |
| GET | /api/v1/strategies/:id |
Get strategy details |
| POST | /api/v1/strategies |
Create strategy |
| PUT | /api/v1/strategies/:id |
Update strategy |
| DELETE | /api/v1/strategies/:id |
Delete strategy |
| POST | /api/v1/strategies/:id/start |
Start strategy |
| POST | /api/v1/strategies/:id/stop |
Stop strategy |
Pools
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/pools |
List available pools |
| GET | /api/v1/pools/:address |
Get pool details |
| GET | /api/v1/pools/:address/state |
Get current pool state |
Analytics
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/analytics/portfolio |
Portfolio analytics |
| POST | /api/v1/analytics/simulate |
Run simulation |
π³ Docker Deployment
The project includes full Docker support for production deployment.
Quick Start with Docker Compose
# Navigate to Docker directory
cd Docker
# Copy environment template
cp .env.example .env
# Start all services
docker-compose up -d
# View logs
docker-compose logs -f
Available Services
| Service | Port | Description |
|---|---|---|
| API | 8080 | REST API server |
| Web | 80 | Web dashboard (Nginx) |
| PostgreSQL | 5432 | Database |
| Prometheus | 9090 | Metrics collection |
| Grafana | 3001 | Monitoring dashboards |
| AlertManager | 9093 | Alert routing |
Docker Images
Pre-built images are available on GitHub Container Registry:
# Pull images
docker pull ghcr.io/joaquinbejar/clmm-liquidity-provider/api:latest
docker pull ghcr.io/joaquinbejar/clmm-liquidity-provider/cli:latest
docker pull ghcr.io/joaquinbejar/clmm-liquidity-provider/web:latest
# Run CLI commands
docker run --rm ghcr.io/joaquinbejar/clmm-liquidity-provider/cli:latest --help
Building Images Locally
# Build all images
docker build -f Docker/api.Dockerfile -t clmm-lp-api .
docker build -f Docker/cli.Dockerfile -t clmm-lp-cli .
docker build -f Docker/web.Dockerfile -t clmm-lp-web .
Monitoring Stack
Start the monitoring infrastructure:
cd Docker/monitoring
docker-compose -f docker-compose.monitoring.yml up -d
Access dashboards:
- Grafana: http://localhost:3001 (admin/admin)
- Prometheus: http://localhost:9090
- AlertManager: http://localhost:9093
π§ͺ Load Testing
Load tests are implemented using k6:
# Install k6
brew install k6 # macOS
# Run smoke test
k6 run --vus 1 --duration 30s tests/load/k6/api-load-test.js
# Run full load test
k6 run tests/load/k6/api-load-test.js
# With custom API URL
k6 run -e API_BASE_URL=http://api.example.com tests/load/k6/api-load-test.js
Test scenarios include:
- Smoke: Verify system works (1 VU, 30s)
- Load: Normal load (20-50 VUs, 9m)
- Stress: Find breaking point (100-200 VUs, 16m)
- Spike: Sudden traffic spike (0-100 VUs)
π CI/CD Pipeline
The project uses GitHub Actions for continuous integration and deployment:
| Workflow | Trigger | Description |
|---|---|---|
| Build | Push/PR | Compile all crates |
| Tests | Push/PR | Run unit and integration tests |
| Lint | Push/PR | Clippy linting |
| Format | Push/PR | rustfmt check |
| Coverage | Push/PR | Code coverage with Codecov |
| Docker | Push to main/tags | Build and push Docker images |
| Semver | Push/PR | Semantic versioning checks |
All workflows run on every push and pull request to ensure code quality.
π€ Contributing
We welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes and ensure tests pass:
make pre-push - Commit with conventional commits:
git commit -m 'feat: add amazing feature' - Push to your fork:
git push origin feature/amazing-feature - Open a Pull Request
Development Guidelines
- Follow Rust idioms and best practices
- Add documentation for all public items
- Write tests for new functionality
- Keep PRs focused and atomic
- Use
make lint-fixbefore committing
π Contact
- Author: JoaquΓn BΓ©jar GarcΓa
- Email: jb@taunais.com
- Telegram: @joaquin_bejar
- Repository: https://github.com/joaquinbejar/CLMM-Liquidity-Provider
- Documentation: https://docs.rs/clmm-liquidity-provider
βοΈ License
This project is dual-licensed under:
- MIT License (LICENSE-MIT or http://opensource.org/licenses/MIT)
- Apache License 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
You may choose either license.
β οΈ Disclaimer
This software is provided for educational and research purposes. Trading cryptocurrencies and providing liquidity involves significant risk. The authors are not responsible for any financial losses incurred through the use of this software. Always do your own research and never invest more than you can afford to lose.
Dependencies
~116MB
~2M SLoC