rustrade-data 0.2.0

High performance & normalised WebSocket intergration for leading cryptocurrency exchanges - batteries included.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Hyperliquid Market Data Integration Tests
//!
//! These tests verify connectivity and data reception from Hyperliquid mainnet.
//!
//! # Running
//!
//! ```bash
//! # Run all Hyperliquid integration tests
//! cargo test --test hyperliquid_data --features hyperliquid -- --ignored
//!
//! # Run specific test
//! cargo test --test hyperliquid_data --features hyperliquid test_historical_candles -- --ignored
//! ```
//!
//! Tests are marked `#[ignore]` to avoid CI failures and rate limiting.

#![cfg(feature = "hyperliquid")]
// Integration test: panics on bad input are acceptable.
#![allow(clippy::unwrap_used, clippy::expect_used)]

use chrono::Duration;
use futures_util::StreamExt;
use rust_decimal::Decimal;
use rustrade_data::{
    exchange::hyperliquid::{
        Hyperliquid,
        historical::{CandleInterval, HistoricalRequest, HyperliquidHistoricalData},
    },
    streams::{
        Streams,
        reconnect::{Event, stream::ReconnectingStream},
    },
    subscriber::WebSocketSubscriber,
    subscription::{book::OrderBooksL2, trade::PublicTrades},
};
use rustrade_instrument::instrument::market_data::kind::MarketDataInstrumentKind;
use std::time::Duration as StdDuration;
use tracing_subscriber::{EnvFilter, fmt};

fn init_logging() {
    let _ = fmt()
        .with_env_filter(
            EnvFilter::builder()
                .with_default_directive(tracing::Level::DEBUG.into())
                .from_env_lossy(),
        )
        .try_init();
}

// ============================================================================
// Historical Data Tests
// ============================================================================

#[tokio::test]
#[ignore]
async fn test_historical_client_creation() {
    init_logging();

    let client = HyperliquidHistoricalData::new(false).await;
    assert!(
        client.is_ok(),
        "Failed to create historical client: {:?}",
        client.err()
    );
}

#[tokio::test]
#[ignore]
async fn test_historical_candles_hourly() {
    init_logging();

    let client = HyperliquidHistoricalData::new(false)
        .await
        .expect("Failed to create client");

    let request = HistoricalRequest::hourly("BTC", 1);
    let candles = client.fetch_candles(request).await;

    assert!(
        candles.is_ok(),
        "Failed to fetch candles: {:?}",
        candles.err()
    );

    let candles = candles.unwrap();
    assert!(!candles.is_empty(), "No candles returned");

    let first = &candles[0];
    assert!(first.open > Decimal::ZERO, "Invalid open price");
    assert!(first.high >= first.low, "High < Low");
    assert!(!first.volume.is_sign_negative(), "Negative volume");

    tracing::info!(count = candles.len(), "Received hourly candles");
}

#[tokio::test]
#[ignore]
async fn test_historical_candles_daily() {
    init_logging();

    let client = HyperliquidHistoricalData::new(false)
        .await
        .expect("Failed to create client");

    let request = HistoricalRequest::daily("ETH", 7);
    let candles = client.fetch_candles(request).await;

    assert!(
        candles.is_ok(),
        "Failed to fetch daily candles: {:?}",
        candles.err()
    );

    let candles = candles.unwrap();
    assert!(!candles.is_empty(), "No daily candles returned");

    tracing::info!(count = candles.len(), "Received daily candles");
}

#[tokio::test]
#[ignore]
async fn test_historical_candles_all_intervals() {
    init_logging();

    let client = HyperliquidHistoricalData::new(false)
        .await
        .expect("Failed to create client");

    let intervals = [
        CandleInterval::Min15,
        CandleInterval::Hour1,
        CandleInterval::Hour4,
        CandleInterval::Day1,
    ];

    for interval in intervals {
        let end_time = chrono::Utc::now();
        let start_time = end_time - Duration::days(1);

        let request = HistoricalRequest {
            coin: "BTC".to_string(),
            interval,
            start_time,
            end_time,
        };

        let result = client.fetch_candles(request).await;
        assert!(
            result.is_ok(),
            "Failed to fetch {:?} candles: {:?}",
            interval,
            result.err()
        );

        tracing::info!(interval = ?interval, count = result.unwrap().len(), "Interval OK");
    }
}

// ============================================================================
// WebSocket Stream Tests
// ============================================================================

#[tokio::test]
#[ignore]
async fn test_trade_stream_connection() {
    init_logging();

    let streams = Streams::<PublicTrades>::builder()
        .subscribe(
            WebSocketSubscriber,
            [(
                Hyperliquid,
                "btc",
                "usdc",
                MarketDataInstrumentKind::Perpetual,
                PublicTrades,
            )],
        )
        .init()
        .await;

    assert!(
        streams.is_ok(),
        "Failed to init trade stream: {:?}",
        streams.err()
    );
    tracing::info!("Trade stream connected");
}

#[tokio::test]
#[ignore]
async fn test_trade_stream_receives_data() {
    init_logging();

    let streams = Streams::<PublicTrades>::builder()
        .subscribe(
            WebSocketSubscriber,
            [(
                Hyperliquid,
                "btc",
                "usdc",
                MarketDataInstrumentKind::Perpetual,
                PublicTrades,
            )],
        )
        .init()
        .await
        .expect("Failed to init stream");

    let mut stream = streams
        .select_all()
        .with_error_handler(|e| tracing::warn!(?e, "Stream error"));

    let deadline = tokio::time::Instant::now() + StdDuration::from_secs(30);

    while tokio::time::Instant::now() < deadline {
        let timeout = tokio::time::timeout(StdDuration::from_secs(10), stream.next()).await;
        assert!(timeout.is_ok(), "Timeout waiting for trade data");

        let event = timeout.unwrap();
        assert!(event.is_some(), "Stream ended without data");

        if let Event::Item(trade) = event.unwrap() {
            tracing::info!(?trade, "Received trade");
            assert!(trade.kind.price > Decimal::ZERO, "Invalid trade price");
            assert!(trade.kind.amount > Decimal::ZERO, "Invalid trade amount");
            return;
        }
    }

    panic!("No trade events received within timeout");
}

#[tokio::test]
#[ignore]
async fn test_l2_book_stream_connection() {
    init_logging();

    let streams = Streams::<OrderBooksL2>::builder()
        .subscribe(
            WebSocketSubscriber,
            [(
                Hyperliquid,
                "btc",
                "usdc",
                MarketDataInstrumentKind::Perpetual,
                OrderBooksL2,
            )],
        )
        .init()
        .await;

    assert!(
        streams.is_ok(),
        "Failed to init L2 book stream: {:?}",
        streams.err()
    );
    tracing::info!("L2 book stream connected");
}

#[tokio::test]
#[ignore]
async fn test_l2_book_stream_receives_data() {
    init_logging();

    let streams = Streams::<OrderBooksL2>::builder()
        .subscribe(
            WebSocketSubscriber,
            [(
                Hyperliquid,
                "btc",
                "usdc",
                MarketDataInstrumentKind::Perpetual,
                OrderBooksL2,
            )],
        )
        .init()
        .await
        .expect("Failed to init stream");

    let mut stream = streams
        .select_all()
        .with_error_handler(|e| tracing::warn!(?e, "Stream error"));

    let timeout = tokio::time::timeout(StdDuration::from_secs(30), stream.next()).await;

    assert!(timeout.is_ok(), "Timeout waiting for L2 book data");
    let event = timeout.unwrap();
    assert!(event.is_some(), "Stream ended without data");

    let book_event = event.unwrap();
    tracing::info!(?book_event, "Received L2 book");
}

#[tokio::test]
#[ignore]
async fn test_multiple_symbols_stream() {
    init_logging();

    let streams = Streams::<PublicTrades>::builder()
        .subscribe(
            WebSocketSubscriber,
            [
                (
                    Hyperliquid,
                    "btc",
                    "usdc",
                    MarketDataInstrumentKind::Perpetual,
                    PublicTrades,
                ),
                (
                    Hyperliquid,
                    "eth",
                    "usdc",
                    MarketDataInstrumentKind::Perpetual,
                    PublicTrades,
                ),
            ],
        )
        .init()
        .await;

    assert!(
        streams.is_ok(),
        "Failed to init multi-symbol stream: {:?}",
        streams.err()
    );

    let mut stream = streams
        .unwrap()
        .select_all()
        .with_error_handler(|e| tracing::warn!(?e, "Stream error"));

    let mut btc_seen = false;
    let mut eth_seen = false;
    let deadline = tokio::time::Instant::now() + StdDuration::from_secs(60);

    while !(btc_seen && eth_seen) && tokio::time::Instant::now() < deadline {
        let timeout = tokio::time::timeout(StdDuration::from_secs(10), stream.next()).await;
        if let Ok(Some(Event::Item(event))) = timeout {
            match event.instrument.base.as_ref() {
                "btc" => {
                    btc_seen = true;
                    tracing::info!("Received BTC trade");
                }
                "eth" => {
                    eth_seen = true;
                    tracing::info!("Received ETH trade");
                }
                _ => {}
            }
        }
    }

    assert!(btc_seen, "No BTC trades received within timeout");
    assert!(eth_seen, "No ETH trades received within timeout");
}

// ============================================================================
// Edge Cases
// ============================================================================

#[tokio::test]
#[ignore]
async fn test_historical_invalid_coin() {
    init_logging();

    let client = HyperliquidHistoricalData::new(false)
        .await
        .expect("Failed to create client");

    let request = HistoricalRequest::hourly("INVALID_COIN_XYZ", 1);
    let result = client.fetch_candles(request).await;

    // Hyperliquid returns empty for unknown coins rather than error
    assert!(
        result.is_ok() && result.unwrap().is_empty(),
        "Expected empty result for invalid coin"
    );
}

#[tokio::test]
#[ignore]
async fn test_historical_testnet() {
    init_logging();

    let client = HyperliquidHistoricalData::new(true).await;
    assert!(
        client.is_ok(),
        "Failed to create testnet client: {:?}",
        client.err()
    );

    let request = HistoricalRequest::hourly("BTC", 1);
    let result = client.unwrap().fetch_candles(request).await;

    // Testnet may have less data but should connect
    assert!(
        result.is_ok(),
        "Testnet candle fetch failed: {:?}",
        result.err()
    );
    tracing::info!(count = result.unwrap().len(), "Testnet candles received");
}