|
| 1 | +# Analysis Tools |
| 2 | + |
| 3 | +A comprehensive Rust library for cryptocurrency arbitrage detection and market analytics. This library provides high-performance tools for analyzing orderbook data, detecting arbitrage opportunities, and calculating market metrics. |
| 4 | + |
| 5 | +## Key Features |
| 6 | + |
| 7 | +### 🔍 Arbitrage Detection |
| 8 | + |
| 9 | +- **Simple Arbitrage**: Detect price differences between exchanges for the same trading pair |
| 10 | +- **Configurable Thresholds**: Set minimum profit and volume thresholds |
| 11 | +- **Multi-Exchange Support**: Analyze opportunities across multiple cryptocurrency exchanges |
| 12 | +- **Real-time Processing**: Async/await support for high-performance real-time analysis |
| 13 | + |
| 14 | +### 📊 Market Analytics |
| 15 | + |
| 16 | +- **Spread Calculation**: Calculate bid-ask spreads for market analysis |
| 17 | +- **VWAP (Volume Weighted Average Price)**: Compute volume-weighted prices across order book levels |
| 18 | +- **Market Summary Analysis**: Process and analyze market summaries from multiple sources |
| 19 | + |
| 20 | +### ⚡ Performance & Scalability |
| 21 | + |
| 22 | +- **High-Performance Processing**: Handle thousands of trading pairs efficiently |
| 23 | +- **Concurrent Processing**: Thread-safe operations for parallel analysis |
| 24 | +- **Memory Efficient**: Optimized for large dataset processing |
| 25 | +- **Configurable Processing Limits**: Built-in timeouts and resource management |
| 26 | + |
| 27 | +### 🧪 Comprehensive Testing |
| 28 | + |
| 29 | +- **Unit Tests**: Extensive test coverage for all components |
| 30 | +- **Integration Tests**: Full integration testing with aggregator-core types |
| 31 | +- **Performance Tests**: Benchmarks for processing time and memory usage |
| 32 | +- **Edge Case Handling**: Robust testing for error conditions and edge cases |
| 33 | + |
| 34 | +## Architecture |
| 35 | + |
| 36 | +```mermaid |
| 37 | +graph TB |
| 38 | + subgraph "Analysis Tools Architecture" |
| 39 | + A[Market Data Input] --> B[ArbitrageDetector] |
| 40 | + A --> C[DefaultAnalysisEngine] |
| 41 | +
|
| 42 | + B --> D[Opportunity Detection] |
| 43 | + C --> E[Spread Calculation] |
| 44 | + C --> F[VWAP Calculation] |
| 45 | +
|
| 46 | + D --> G[Filtered Opportunities] |
| 47 | + E --> H[Market Metrics] |
| 48 | + F --> H |
| 49 | +
|
| 50 | + G --> I[Output: ArbitrageOpportunity] |
| 51 | + H --> J[Output: Market Analytics] |
| 52 | + end |
| 53 | +
|
| 54 | + subgraph "Core Components" |
| 55 | + K[ArbitrageDetector] |
| 56 | + L[AnalysisEngine Trait] |
| 57 | + M[DefaultAnalysisEngine] |
| 58 | + end |
| 59 | +
|
| 60 | + subgraph "Data Flow" |
| 61 | + N[TradingPair + Summary] --> O[Analysis Processing] |
| 62 | + O --> P[Threshold Filtering] |
| 63 | + P --> Q[Results] |
| 64 | + end |
| 65 | +``` |
| 66 | + |
| 67 | +### Core Components |
| 68 | + |
| 69 | +#### ArbitrageDetector |
| 70 | + |
| 71 | +The main component for detecting arbitrage opportunities: |
| 72 | + |
| 73 | +- Configurable profit and volume thresholds |
| 74 | +- Multi-exchange comparison logic |
| 75 | +- Async processing for real-time analysis |
| 76 | +- Future support for triangular arbitrage and negative cycle detection |
| 77 | + |
| 78 | +#### AnalysisEngine Trait |
| 79 | + |
| 80 | +Defines the interface for market analysis operations: |
| 81 | + |
| 82 | +- `analyze_summaries()`: Find arbitrage opportunities in market data |
| 83 | +- `calculate_spread()`: Compute bid-ask spreads |
| 84 | +- `calculate_volume_weighted_price()`: Calculate VWAP |
| 85 | + |
| 86 | +#### DefaultAnalysisEngine |
| 87 | + |
| 88 | +Default implementation of the AnalysisEngine trait: |
| 89 | + |
| 90 | +- Efficient summary analysis |
| 91 | +- Robust spread and VWAP calculations |
| 92 | +- Integration with aggregator-core types |
| 93 | + |
| 94 | +## How to Use |
| 95 | + |
| 96 | +### Basic Usage |
| 97 | + |
| 98 | +```rust |
| 99 | +use analysis_tools::{ArbitrageDetector, AnalysisEngine, DefaultAnalysisEngine}; |
| 100 | +use aggregator_core::{TradingPair, Summary, Exchange}; |
| 101 | +use std::collections::HashMap; |
| 102 | + |
| 103 | +#[tokio::main] |
| 104 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 105 | + // Create an arbitrage detector with custom thresholds |
| 106 | + let detector = ArbitrageDetector::new( |
| 107 | + 0.1, // 0.1% minimum profit threshold |
| 108 | + 0.01 // 0.01 minimum volume threshold |
| 109 | + ); |
| 110 | + |
| 111 | + // Prepare market data (TradingPair -> Vec<Summary>) |
| 112 | + let mut market_data = HashMap::new(); |
| 113 | + let btc_pair = TradingPair::new("BTC", "USDT"); |
| 114 | + |
| 115 | + // Add summaries from different exchanges |
| 116 | + let summaries = vec![ |
| 117 | + create_binance_summary(), |
| 118 | + create_bybit_summary(), |
| 119 | + ]; |
| 120 | + market_data.insert(btc_pair, summaries); |
| 121 | + |
| 122 | + // Detect arbitrage opportunities |
| 123 | + let opportunities = detector.detect_opportunities(&market_data).await; |
| 124 | + |
| 125 | + for opportunity in opportunities { |
| 126 | + println!("Arbitrage Opportunity:"); |
| 127 | + println!(" Symbol: {}", opportunity.symbol); |
| 128 | + println!(" Buy on: {:?} at ${:.2}", opportunity.buy_exchange, opportunity.buy_price); |
| 129 | + println!(" Sell on: {:?} at ${:.2}", opportunity.sell_exchange, opportunity.sell_price); |
| 130 | + println!(" Profit: {:.2}%", opportunity.profit_percentage); |
| 131 | + println!(" Volume: {:.4}", opportunity.volume); |
| 132 | + } |
| 133 | + |
| 134 | + Ok(()) |
| 135 | +} |
| 136 | +``` |
| 137 | + |
| 138 | +### Using the Analysis Engine |
| 139 | + |
| 140 | +```rust |
| 141 | +use analysis_tools::{AnalysisEngine, DefaultAnalysisEngine}; |
| 142 | +use std::collections::HashMap; |
| 143 | + |
| 144 | +#[tokio::main] |
| 145 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 146 | + let engine = DefaultAnalysisEngine::new(); |
| 147 | + |
| 148 | + // Prepare summaries (String -> Summary mapping) |
| 149 | + let mut summaries = HashMap::new(); |
| 150 | + summaries.insert("binance_btcusdt".to_string(), create_summary()); |
| 151 | + |
| 152 | + // Analyze summaries for arbitrage |
| 153 | + let opportunities = engine.analyze_summaries(&summaries).await?; |
| 154 | + |
| 155 | + // Calculate market metrics |
| 156 | + let summary = summaries.values().next().unwrap(); |
| 157 | + let spread = engine.calculate_spread(summary).await; |
| 158 | + let vwap = engine.calculate_volume_weighted_price(summary).await; |
| 159 | + |
| 160 | + println!("Found {} arbitrage opportunities", opportunities.len()); |
| 161 | + println!("Spread: {:?}", spread); |
| 162 | + println!("VWAP: {:?}", vwap); |
| 163 | + |
| 164 | + Ok(()) |
| 165 | +} |
| 166 | +``` |
| 167 | + |
| 168 | +### Advanced Configuration |
| 169 | + |
| 170 | +```rust |
| 171 | +use analysis_tools::ArbitrageDetector; |
| 172 | + |
| 173 | +// Create detector with strict thresholds for high-frequency trading |
| 174 | +let hft_detector = ArbitrageDetector::new( |
| 175 | + 0.05, // 0.05% minimum profit (tighter threshold) |
| 176 | + 1.0 // 1.0 minimum volume (higher volume requirement) |
| 177 | +); |
| 178 | + |
| 179 | +// Create detector with relaxed thresholds for larger opportunities |
| 180 | +let swing_detector = ArbitrageDetector::new( |
| 181 | + 0.5, // 0.5% minimum profit (higher threshold) |
| 182 | + 0.001 // 0.001 minimum volume (lower volume requirement) |
| 183 | +); |
| 184 | +``` |
| 185 | + |
| 186 | +## Integration with Aggregator Core |
| 187 | + |
| 188 | +This library is designed to work seamlessly with the `aggregator-core` crate: |
| 189 | + |
| 190 | +```rust |
| 191 | +use aggregator_core::{Aggregator, Config}; |
| 192 | +use analysis_tools::ArbitrageDetector; |
| 193 | + |
| 194 | +#[tokio::main] |
| 195 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 196 | + // Set up aggregator |
| 197 | + let config = Config::default(); |
| 198 | + let aggregator = Aggregator::new(config); |
| 199 | + |
| 200 | + // Set up analysis tools |
| 201 | + let detector = ArbitrageDetector::default(); |
| 202 | + |
| 203 | + // Subscribe to real-time summaries |
| 204 | + let mut summary_rx = aggregator.subscribe_summaries(); |
| 205 | + |
| 206 | + // Process summaries in real-time |
| 207 | + while let Ok(summary) = summary_rx.recv().await { |
| 208 | + // Convert to analysis format and process |
| 209 | + // ... processing logic |
| 210 | + } |
| 211 | + |
| 212 | + Ok(()) |
| 213 | +} |
| 214 | +``` |
| 215 | + |
| 216 | +## Testing |
| 217 | + |
| 218 | +The library includes comprehensive test suites: |
| 219 | + |
| 220 | +### Running Tests |
| 221 | + |
| 222 | +```bash |
| 223 | +# Run all tests |
| 224 | +cargo test |
| 225 | + |
| 226 | +# Run specific test categories |
| 227 | +cargo test --test arbitrage_detector_tests |
| 228 | +cargo test --test performance_integration_tests |
| 229 | + |
| 230 | +# Run with output |
| 231 | +cargo test -- --nocapture |
| 232 | +``` |
| 233 | + |
| 234 | +### Test Categories |
| 235 | + |
| 236 | +1. **Unit Tests**: Core functionality testing |
| 237 | +2. **Integration Tests**: Cross-component integration |
| 238 | +3. **Performance Tests**: Processing time and memory usage |
| 239 | +4. **Edge Case Tests**: Error handling and boundary conditions |
| 240 | + |
| 241 | +### Performance Benchmarks |
| 242 | + |
| 243 | +The library is tested to handle: |
| 244 | + |
| 245 | +- 1000+ trading pairs in under 3 seconds |
| 246 | +- Real-time processing with sub-millisecond latency |
| 247 | +- Concurrent processing across multiple threads |
| 248 | +- Large datasets with efficient memory usage |
| 249 | + |
| 250 | +## Dependencies |
| 251 | + |
| 252 | +```toml |
| 253 | +[dependencies] |
| 254 | +aggregator-core = { path = "../aggregator-core" } |
| 255 | +tokio = { workspace = true } |
| 256 | +serde = { workspace = true } |
| 257 | +async-trait = { workspace = true } |
| 258 | +chrono = { workspace = true } |
| 259 | + |
| 260 | +[dev-dependencies] |
| 261 | +futures = "0.3" |
| 262 | +``` |
| 263 | + |
| 264 | +## Contributing |
| 265 | + |
| 266 | +1. Fork the repository |
| 267 | +2. Create a feature branch |
| 268 | +3. Add tests for new functionality |
| 269 | +4. Ensure all tests pass |
| 270 | +5. Submit a pull request |
| 271 | + |
| 272 | +## License |
| 273 | + |
| 274 | +This project is licensed under the MIT License - see the LICENSE file for details. |
| 275 | + |
| 276 | +## Future Enhancements |
| 277 | + |
| 278 | +- **Triangular Arbitrage**: Detection of three-way arbitrage opportunities |
| 279 | +- **Negative Cycle Detection**: Bellman-Ford algorithm for complex arbitrage paths |
| 280 | +- **Machine Learning Integration**: Predictive arbitrage opportunity detection |
| 281 | +- **Advanced Metrics**: Additional market analysis tools and indicators |
0 commit comments