Hyperliquid Backtester
A comprehensive Rust library that integrates Hyperliquid trading data with the rs-backtester framework to enable sophisticated backtesting of trading strategies using real Hyperliquid market data, including perpetual futures mechanics and funding rate calculations.
โจ Features
- ๐ Async Data Fetching: Efficiently fetch historical OHLC data from Hyperliquid API using the official SDK
- ๐ฐ Funding Rate Support: Complete funding rate data and perpetual futures mechanics
- ๐ Seamless Integration: Drop-in replacement for rs-backtester with enhanced features
- ๐ Enhanced Reporting: Comprehensive metrics including funding PnL and arbitrage analysis
- โก High Performance: Optimized for large datasets and complex multi-asset strategies
- ๐ก๏ธ Type Safety: Comprehensive error handling with detailed error messages
- ๐ Advanced Strategies: Built-in funding arbitrage and enhanced technical indicators
- ๐ง Developer Friendly: Extensive documentation, examples, and migration guides
- ๐ Structured Logging: Built-in logging and debugging support with configurable output
- ๐ด Real-Time Monitoring: Live trading monitoring with alerts and performance tracking
- ๐ฑ Trading Modes: Support for backtesting, paper trading, and live trading modes
- ๐ฏ Risk Management: Advanced risk controls and position management
- ๐ Unified Data Interface: Consistent API across different trading modes
- ๐ Alert System: Configurable alerts for market conditions and performance metrics
- ๐งฌ Genetic Optimization: Built-in GA framework for tuning strategy hyperparameters
๐ฆ Installation
Add this to your Cargo.toml:
[]
= "0.1.1"
= { = "1.0", = ["full"] }
= { = "0.4", = ["serde"] }
System Requirements
- Rust: 1.70 or later
- Operating System: Linux, macOS, or Windows
- Memory: Minimum 4GB RAM (8GB+ recommended for large datasets)
- Network: Internet connection required for Hyperliquid API access
๐ Quick Start
Working Data Fetching Example
use ;
use ;
async
Working Backtesting Example
use *;
use ;
use ;
async
Genetic Hyperparameter Optimization
The crate ships with a reusable genetic algorithm engine that can search strategy
parameters for you. Implement the Genome
trait for your configuration, provide an evaluation function, and let the
optimizer explore the space. The bundled example downloads real candles via the
official SDK and tunes the SMA crossover strategy end-to-end:
The optimizer reports the best candidate per generation together with the metrics returned by your evaluator. This makes it easy to compare fitness scores, inspect Sharpe/return/drawdown trade-offs, or integrate a custom scoring function.
Real-Time Monitoring Example
use *;
use ;
use AlertLevel;
async
๐ Usage Guide
Data Fetching with Working SDK
The library now uses the official Hyperliquid Rust SDK for reliable data fetching:
use ;
// Initialize client
let info_client = new.await?;
// Fetch data for different intervals
let candles = info_client
.candles_snapshot
.await?;
// Supported intervals: "1m", "5m", "15m", "1h", "4h", "1d"
// Supported coins: BTC, ETH, SOL, AVAX, MATIC, ATOM, and many more
Trading Modes
The library supports multiple trading modes through the unified interface:
use *;
// Backtesting mode
let backtest_mode = Backtest;
let mut backtest = new?;
// Paper trading mode
let paper_mode = PaperTrade;
let mut paper_trader = new?;
// Live trading mode (with safety controls)
let live_mode = LiveTrade;
let mut live_trader = new?;
Real-Time Monitoring
Monitor your trading performance in real-time:
use *;
// Start monitoring server
let mut server = new;
server.start.await?;
// Create monitoring manager
let mut manager = new;
// Add custom alert handlers
manager.add_alert_handler;
// Update metrics
manager.update_performance_metrics?;
Risk Management
Advanced risk controls for live trading:
use *;
let risk_config = RiskConfig ;
let risk_manager = new;
Enhanced Reporting
Generate comprehensive reports with new metrics:
// Standard enhanced report
let report = backtest.enhanced_report?;
println!;
println!;
// Funding-specific report
let funding_report = backtest.funding_report?;
println!;
println!;
// Mode-specific reporting
let mode_report = backtest.mode_report?;
println!;
println!;
// Export to CSV with enhanced data
backtest.export_enhanced_csv?;
Unified Data Interface
Consistent API across all trading modes:
use *;
// Create order requests
let market_order = market;
let limit_order = limit
.reduce_only
.with_time_in_force;
// Market data
let market_data = new;
// Position management
let mut position = new;
position.update_price;
position.apply_funding_payment;
๐ API Stability
This crate follows Semantic Versioning (SemVer):
- Major version (0.x.y โ 1.0.0): Breaking API changes
- Minor version (0.1.x โ 0.2.0): New features, backward compatible
- Patch version (0.1.0 โ 0.1.1): Bug fixes, backward compatible
Current version: 0.1.1 (Pre-1.0 development phase)
Stability Guarantees
- โ
Public API: All items in the
preludemodule are considered stable within minor versions - โ
Data Structures:
HyperliquidData,HyperliquidBacktest, andHyperliquidCommissionare stable - โ
Error Types:
HyperliquidBacktestErrorvariants may be added but not removed in minor versions - โ
Strategy Interface:
HyperliquidStrategytrait is stable for implementors - โ
Unified Interface:
OrderRequest,MarketData,Positionstructures are stable
๐ Examples
The library includes comprehensive examples in the examples/ directory:
Working Examples (Recommended)
working_data_fetch.rs: Reliable data fetching using the official SDKsimple_working_backtest.rs: Complete working backtest examplebasic_backtest.rs: Enhanced basic backtesting workflow
Advanced Features
real_time_monitoring_example.rs: Live monitoring with alertstrading_mode_example.rs: Different trading modes demonstrationpaper_trading_example.rs: Paper trading with risk managementlive_trading_safety_example.rs: Safe live trading practicesfunding_arbitrage_advanced.rs: Advanced funding arbitrage strategiesmulti_asset_backtest.rs: Multi-asset portfolio backtestingstrategy_comparison.rs: Compare multiple strategiesperformance_comparison.rs: Performance analysis tools
Data and Export
csv_export_example.rs: Data export and analysisenhanced_csv_export_example.rs: Advanced CSV export with funding dataunified_data_example.rs: Unified data interface usage
Run examples with:
# Working examples (recommended to start with)
# Advanced features
๐ ๏ธ Advanced Features
Performance Monitoring
Track performance of operations with built-in spans:
use *;
use Instrument;
async
Error Handling
Comprehensive error handling with detailed context:
use *;
match fetch.await
Migration from rs-backtester
This library is designed as a drop-in enhancement to rs-backtester:
// Before (rs-backtester)
use *;
let data = from_csv?;
// After (hyperliquid-backtest)
use *;
let data = fetch.await?;
let rs_data = data.to_rs_backtester_data; // Convert if needed
๐งช Testing
Run the test suite:
# Run all tests
# Run with logging
RUST_LOG=debug
# Run specific test module
# Run benchmarks
๐ Performance
The library is optimized for performance with large datasets:
- Memory Efficient: Streaming data processing for large time ranges
- Async Operations: Non-blocking API calls and data processing
- Caching: Intelligent caching of funding rate data
- Parallel Processing: Multi-threaded backtesting for complex strategies
Benchmark results on a modern system:
- Data Fetching: ~500ms for 30 days of 1h data
- Backtesting: ~50ms for 1000 trades with funding calculations
- Memory Usage: ~10MB for 30 days of 1h OHLC + funding data
- Real-Time Monitoring: <1ms latency for alert processing
๐ค Contributing
Contributions are welcome! Please see our Contributing Guide for details.
Development Setup
Code Style
We use rustfmt and clippy for code formatting and linting:
๐ License
This project is dual-licensed under the MIT OR Apache-2.0 license.
โ ๏ธ Disclaimer
This is an experimental library. Use at your own risk. All actions are performed at your own risk.
This software is for educational and research purposes only. Trading cryptocurrencies involves substantial risk and may not be suitable for all investors. Past performance does not guarantee future results.
Important Notes:
- Always test strategies thoroughly before using real capital
- Be aware of API rate limits when fetching large amounts of data
- Funding rates and market conditions can change rapidly
- Consider transaction costs and slippage in live trading
- Use paper trading mode to test strategies before live deployment
- Monitor your positions and set appropriate risk controls
๐ Links
๐ Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: docs.rs