hyperliquid_backtest/
migration.rs

1//! # Migration Guide from rs-backtester
2//!
3//! This module provides comprehensive guidance for migrating existing rs-backtester code
4//! to use hyperliquid-backtester with enhanced Hyperliquid-specific features.
5//!
6//! ## Overview
7//!
8//! hyperliquid-backtester is designed as a drop-in enhancement to rs-backtester, meaning
9//! most existing code will work with minimal changes while gaining access to:
10//!
11//! - Real Hyperliquid market data
12//! - Funding rate calculations
13//! - Enhanced commission structures
14//! - Perpetual futures mechanics
15//! - Advanced reporting features
16//!
17//! ## Basic Migration Steps
18//!
19//! ### 1. Update Dependencies
20//!
21//! **Before (rs-backtester only):**
22//! ```toml
23//! [dependencies]
24//! rs-backtester = "0.1"
25//! ```
26//!
27//! **After (with hyperliquid-backtester):**
28//! ```toml
29//! [dependencies]
30//! hyperliquid-backtester = "0.1"
31//! tokio = { version = "1.0", features = ["full"] }
32//! ```
33//!
34//! ### 2. Update Imports
35//!
36//! **Before:**
37//! ```rust,ignore
38//! use rs_backtester::prelude::*;
39//! ```
40//!
41//! **After:**
42//! ```rust,ignore
43//! use hyperliquid_backtest::prelude::*;
44//! ```
45//!
46//! ### 3. Replace Data Sources
47//!
48//! **Before (CSV or manual data):**
49//! ```rust,ignore
50//! let data = Data::from_csv("data.csv")?;
51//! ```
52//!
53//! **After (Live Hyperliquid data):**
54//! ```rust,ignore
55//! let data = HyperliquidData::fetch("BTC", "1h", start_time, end_time).await?;
56//! ```
57//!
58//! ## Detailed Migration Examples
59//!
60//! ### Example 1: Simple Moving Average Strategy
61//!
62//! **Before (rs-backtester):**
63//! ```rust,ignore
64//! use rs_backtester::prelude::*;
65//!
66//! fn main() -> Result<(), Box<dyn std::error::Error>> {
67//!     let data = Data::from_csv("btc_data.csv")?;
68//!     
69//!     let strategy = sma_cross(data.clone(), 10, 20);
70//!     
71//!     let mut backtest = Backtest::new(
72//!         data,
73//!         strategy,
74//!         10000.0,
75//!         Commission { rate: 0.001 },
76//!     );
77//!     
78//!     backtest.run();
79//!     let report = backtest.report();
80//!     
81//!     println!("Total Return: {:.2}%", report.total_return * 100.0);
82//!     
83//!     Ok(())
84//! }
85//! ```
86//!
87//! **After (hyperliquid-backtester):**
88//! ```rust,ignore
89//! use hyperliquid_backtest::prelude::*;
90//!
91//! #[tokio::main]
92//! async fn main() -> Result<(), HyperliquidBacktestError> {
93//!     // Fetch real Hyperliquid data
94//!     let data = HyperliquidData::fetch("BTC", "1h", start_time, end_time).await?;
95//!     
96//!     // Use enhanced SMA strategy with funding awareness
97//!     let strategy = enhanced_sma_cross(10, 20, Default::default())?;
98//!     
99//!     let mut backtest = HyperliquidBacktest::new(
100//!         data,
101//!         strategy,
102//!         10000.0,
103//!         HyperliquidCommission::default(), // Realistic Hyperliquid fees
104//!     )?;
105//!     
106//!     // Include funding calculations
107//!     backtest.calculate_with_funding()?;
108//!     let report = backtest.enhanced_report()?;
109//!     
110//!     println!("Total Return: {:.2}%", report.total_return * 100.0);
111//!     println!("Funding PnL: ${:.2}", report.funding_pnl); // New!
112//!     
113//!     Ok(())
114//! }
115//! ```
116//!
117//! ### Example 2: Custom Strategy Migration
118//!
119//! **Before (rs-backtester custom strategy):**
120//! ```rust,ignore
121//! use rs_backtester::prelude::*;
122//!
123//! fn rsi_strategy(data: Data, period: usize, oversold: f64, overbought: f64) -> Strategy {
124//!     let mut strategy = Strategy::new();
125//!     
126//!     strategy.next(Box::new(move |ctx, _| {
127//!         let rsi = calculate_rsi(&ctx.data().close, period, ctx.index());
128//!         
129//!         if rsi < oversold {
130//!             ctx.entry_qty(1.0); // Go long
131//!         } else if rsi > overbought {
132//!             ctx.entry_qty(-1.0); // Go short
133//!         }
134//!     }));
135//!     
136//!     strategy
137//! }
138//! ```
139//!
140//! **After (hyperliquid-backtester with funding awareness):**
141//! ```rust,ignore
142//! use hyperliquid_backtest::prelude::*;
143//!
144//! fn enhanced_rsi_strategy(
145//!     data: &HyperliquidData, 
146//!     period: usize, 
147//!     oversold: f64, 
148//!     overbought: f64,
149//!     funding_config: FundingAwareConfig,
150//! ) -> Result<Strategy, HyperliquidBacktestError> {
151//!     let mut strategy = Strategy::new();
152//!     let data_clone = data.clone();
153//!     
154//!     strategy.next(Box::new(move |ctx, _| {
155//!         let rsi = calculate_rsi(&ctx.data().close, period, ctx.index());
156//!         
157//!         // Get funding rate for current timestamp
158//!         let current_time = data_clone.datetime[ctx.index()];
159//!         let funding_rate = data_clone.get_funding_rate_at(current_time).unwrap_or(0.0);
160//!         
161//!         // Combine RSI and funding signals
162//!         let mut signal = 0.0;
163//!         
164//!         if rsi < oversold {
165//!             signal = 1.0; // RSI suggests long
166//!         } else if rsi > overbought {
167//!             signal = -1.0; // RSI suggests short
168//!         }
169//!         
170//!         // Adjust signal based on funding rate
171//!         if funding_rate.abs() > funding_config.funding_threshold {
172//!             if funding_rate > 0.0 {
173//!                 // Positive funding - longs pay shorts, favor long
174//!                 signal += funding_config.funding_weight;
175//!             } else {
176//!                 // Negative funding - shorts pay longs, favor short
177//!                 signal -= funding_config.funding_weight;
178//!             }
179//!         }
180//!         
181//!         // Apply final signal
182//!         if signal > 0.5 {
183//!             ctx.entry_qty(1.0);
184//!         } else if signal < -0.5 {
185//!             ctx.entry_qty(-1.0);
186//!         } else {
187//!             ctx.exit();
188//!         }
189//!     }));
190//!     
191//!     Ok(strategy)
192//! }
193//! ```
194//!
195//! ## Key Differences and Enhancements
196//!
197//! ### 1. Async Operations
198//!
199//! hyperliquid-backtester uses async operations for data fetching:
200//!
201//! ```rust,ignore
202//! // Always use #[tokio::main] for async main function
203//! #[tokio::main]
204//! async fn main() -> Result<(), HyperliquidBacktestError> {
205//!     let data = HyperliquidData::fetch("BTC", "1h", start, end).await?;
206//!     // ... rest of code
207//! }
208//! ```
209//!
210//! ### 2. Enhanced Commission Structure
211//!
212//! **rs-backtester:**
213//! ```rust,ignore
214//! Commission { rate: 0.001 } // Single rate for all trades
215//! ```
216//!
217//! **hyperliquid-backtester:**
218//! ```rust,ignore
219//! HyperliquidCommission {
220//!     maker_rate: 0.0002,    // 0.02% for maker orders
221//!     taker_rate: 0.0005,    // 0.05% for taker orders
222//!     funding_enabled: true, // Include funding calculations
223//! }
224//! ```
225//!
226//! ### 3. Enhanced Reporting
227//!
228//! **rs-backtester:**
229//! ```rust,ignore
230//! let report = backtest.report();
231//! println!("Return: {:.2}%", report.total_return * 100.0);
232//! ```
233//!
234//! **hyperliquid-backtester:**
235//! ```rust,ignore
236//! let report = backtest.enhanced_report()?;
237//! println!("Trading Return: {:.2}%", report.trading_return * 100.0);
238//! println!("Funding Return: {:.2}%", report.funding_return * 100.0);
239//! println!("Total Return: {:.2}%", report.total_return * 100.0);
240//! 
241//! // Additional funding-specific metrics
242//! let funding_report = backtest.funding_report()?;
243//! println!("Avg Funding Rate: {:.4}%", funding_report.avg_funding_rate * 100.0);
244//! ```
245//!
246//! ## Common Migration Patterns
247//!
248//! ### Pattern 1: Data Loading
249//!
250//! **From CSV files:**
251//! ```rust,ignore
252//! // Old
253//! let data = Data::from_csv("data.csv")?;
254//!
255//! // New - convert existing CSV to HyperliquidData format
256//! let data = HyperliquidData::from_csv("data.csv").await?;
257//! // Or fetch fresh data
258//! let data = HyperliquidData::fetch("BTC", "1h", start, end).await?;
259//! ```
260//!
261//! ### Pattern 2: Strategy Enhancement
262//!
263//! **Add funding awareness to existing strategies:**
264//! ```rust,ignore
265//! // Wrap existing rs-backtester strategy
266//! let base_strategy = your_existing_strategy();
267//! let enhanced_strategy = base_strategy.with_funding_awareness(0.0001)?;
268//! ```
269//!
270//! ### Pattern 3: Error Handling
271//!
272//! **Update error handling:**
273//! ```rust,ignore
274//! // Old
275//! fn run_backtest() -> Result<(), Box<dyn std::error::Error>> {
276//!     // ...
277//! }
278//!
279//! // New
280//! async fn run_backtest() -> Result<(), HyperliquidBacktestError> {
281//!     // ...
282//! }
283//! ```
284//!
285//! ## Compatibility Notes
286//!
287//! ### What Stays the Same
288//!
289//! - Core strategy logic and indicators
290//! - Basic backtest workflow
291//! - Report structure (with additions)
292//! - CSV export functionality (enhanced)
293//!
294//! ### What Changes
295//!
296//! - Data fetching becomes async
297//! - Commission structure is more detailed
298//! - Error types are more specific
299//! - Additional funding-related methods
300//!
301//! ### Breaking Changes
302//!
303//! 1. **Async requirement**: Data fetching requires async context
304//! 2. **Error types**: `HyperliquidBacktestError` instead of generic errors
305//! 3. **Commission structure**: More detailed fee structure
306//! 4. **Import paths**: Use `hyperliquid_backtest::prelude::*`
307//!
308//! ## Migration Checklist
309//!
310//! - [ ] Update `Cargo.toml` dependencies
311//! - [ ] Change imports to `hyperliquid_backtest::prelude::*`
312//! - [ ] Add `#[tokio::main]` to main function
313//! - [ ] Replace data loading with `HyperliquidData::fetch()`
314//! - [ ] Update commission structure to `HyperliquidCommission`
315//! - [ ] Update error handling to use `HyperliquidBacktestError`
316//! - [ ] Test enhanced features (funding calculations, etc.)
317//! - [ ] Update documentation and examples
318//!
319//! ## Getting Help
320//!
321//! If you encounter issues during migration:
322//!
323//! 1. Check the [API documentation](https://docs.rs/hyperliquid-backtester)
324//! 2. Review the [examples directory](https://github.com/xsa-dev/hyperliquid-backtester/tree/main/examples)
325//! 3. Open an issue on [GitHub](https://github.com/xsa-dev/hyperliquid-backtester/issues)
326//!
327//! ## Performance Considerations
328//!
329//! - **Data fetching**: Cache data locally for repeated backtests
330//! - **Funding calculations**: Can be disabled if not needed via `funding_enabled: false`
331//! - **Memory usage**: HyperliquidData includes additional funding rate arrays
332//! - **Network calls**: Batch data requests when possible