asterdex-sdk 0.1.1

AsterDex Futures SDK v3 — Rust async client for REST and WebSocket APIs
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// US-001: Market data endpoints stub — implemented in US-006, US-007
// US-006: get_server_time endpoint
// US-007: public market data endpoints (ping, exchange info, depth, trades, klines, tickers, etc.)

use crate::futures::models::market::{
    AggTrade, BookTickerShape, DepthResponse, ExchangeInfoResponse, FundingInfoResponse,
    FundingRateRecord, Kline, KlineInterval, MarkPriceShape, PingResponse, ServerTimeResponse,
    Ticker24hrShape, TickerPriceShape, TradeRecord,
};
use crate::rest::client::RestClient;
use crate::rest::error::AsterDexError;
use crate::rest::response::ApiResponse;

impl RestClient {
    /// Get server time in milliseconds.
    ///
    /// Use to detect clock drift before placing orders.
    /// This is a public endpoint (no authentication required).
    pub async fn get_server_time(&self) -> Result<ApiResponse<ServerTimeResponse>, AsterDexError> {
        self.get("/fapi/v3/time", &[]).await
    }

    // -------------------------------------------------------------------------
    // US-007: Public market data endpoints
    // -------------------------------------------------------------------------

    /// Ping the REST API to check connectivity.
    ///
    /// Public endpoint — no authentication required.
    pub async fn ping(&self) -> Result<ApiResponse<PingResponse>, AsterDexError> {
        self.get("/fapi/v3/ping", &[]).await
    }

    /// Get exchange information including all trading symbols.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_exchange_info(&self) -> Result<ApiResponse<ExchangeInfoResponse>, AsterDexError> {
        self.get("/fapi/v3/exchangeInfo", &[]).await
    }

    /// Get order book depth for a symbol.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_depth(
        &self,
        symbol: &str,
        limit: Option<u32>,
    ) -> Result<ApiResponse<DepthResponse>, AsterDexError> {
        let limit_str;
        let mut params = vec![("symbol", symbol)];
        if let Some(l) = limit {
            limit_str = l.to_string();
            params.push(("limit", &limit_str));
        }
        self.get("/fapi/v3/depth", &params).await
    }

    /// Get recent trades for a symbol.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_trades(
        &self,
        symbol: &str,
        limit: Option<u32>,
    ) -> Result<ApiResponse<Vec<TradeRecord>>, AsterDexError> {
        let limit_str;
        let mut params = vec![("symbol", symbol)];
        if let Some(l) = limit {
            limit_str = l.to_string();
            params.push(("limit", &limit_str));
        }
        self.get("/fapi/v3/trades", &params).await
    }

    /// Get historical (older) trades for a symbol.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_historical_trades(
        &self,
        symbol: &str,
        limit: Option<u32>,
        from_id: Option<i64>,
    ) -> Result<ApiResponse<Vec<TradeRecord>>, AsterDexError> {
        let limit_str;
        let from_id_str;
        let mut params = vec![("symbol", symbol)];
        if let Some(l) = limit {
            limit_str = l.to_string();
            params.push(("limit", &limit_str));
        }
        if let Some(id) = from_id {
            from_id_str = id.to_string();
            params.push(("fromId", &from_id_str));
        }
        self.get("/fapi/v3/historicalTrades", &params).await
    }

    /// Get compressed/aggregate trades for a symbol.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_agg_trades(
        &self,
        symbol: &str,
        from_id: Option<i64>,
        start_time: Option<u64>,
        end_time: Option<u64>,
        limit: Option<u32>,
    ) -> Result<ApiResponse<Vec<AggTrade>>, AsterDexError> {
        let from_id_str;
        let start_time_str;
        let end_time_str;
        let limit_str;
        let mut params = vec![("symbol", symbol)];
        if let Some(id) = from_id {
            from_id_str = id.to_string();
            params.push(("fromId", &from_id_str));
        }
        if let Some(st) = start_time {
            start_time_str = st.to_string();
            params.push(("startTime", &start_time_str));
        }
        if let Some(et) = end_time {
            end_time_str = et.to_string();
            params.push(("endTime", &end_time_str));
        }
        if let Some(l) = limit {
            limit_str = l.to_string();
            params.push(("limit", &limit_str));
        }
        self.get("/fapi/v3/aggTrades", &params).await
    }

    /// Get kline/candlestick data for a symbol.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_klines(
        &self,
        symbol: &str,
        interval: KlineInterval,
        start_time: Option<u64>,
        end_time: Option<u64>,
        limit: Option<u32>,
    ) -> Result<ApiResponse<Vec<Kline>>, AsterDexError> {
        let start_time_str;
        let end_time_str;
        let limit_str;
        let interval_str = interval.to_str();
        let mut params = vec![("symbol", symbol), ("interval", interval_str)];
        if let Some(st) = start_time {
            start_time_str = st.to_string();
            params.push(("startTime", &start_time_str));
        }
        if let Some(et) = end_time {
            end_time_str = et.to_string();
            params.push(("endTime", &end_time_str));
        }
        if let Some(l) = limit {
            limit_str = l.to_string();
            params.push(("limit", &limit_str));
        }
        self.get("/fapi/v3/klines", &params).await
    }

    /// Get kline/candlestick data for an index price.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_index_price_klines(
        &self,
        pair: &str,
        interval: KlineInterval,
        start_time: Option<u64>,
        end_time: Option<u64>,
        limit: Option<u32>,
    ) -> Result<ApiResponse<Vec<Kline>>, AsterDexError> {
        let start_time_str;
        let end_time_str;
        let limit_str;
        let interval_str = interval.to_str();
        let mut params = vec![("pair", pair), ("interval", interval_str)];
        if let Some(st) = start_time {
            start_time_str = st.to_string();
            params.push(("startTime", &start_time_str));
        }
        if let Some(et) = end_time {
            end_time_str = et.to_string();
            params.push(("endTime", &end_time_str));
        }
        if let Some(l) = limit {
            limit_str = l.to_string();
            params.push(("limit", &limit_str));
        }
        self.get("/fapi/v3/indexPriceKlines", &params).await
    }

    /// Get kline/candlestick data for a mark price.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_mark_price_klines(
        &self,
        symbol: &str,
        interval: KlineInterval,
        start_time: Option<u64>,
        end_time: Option<u64>,
        limit: Option<u32>,
    ) -> Result<ApiResponse<Vec<Kline>>, AsterDexError> {
        let start_time_str;
        let end_time_str;
        let limit_str;
        let interval_str = interval.to_str();
        let mut params = vec![("symbol", symbol), ("interval", interval_str)];
        if let Some(st) = start_time {
            start_time_str = st.to_string();
            params.push(("startTime", &start_time_str));
        }
        if let Some(et) = end_time {
            end_time_str = et.to_string();
            params.push(("endTime", &end_time_str));
        }
        if let Some(l) = limit {
            limit_str = l.to_string();
            params.push(("limit", &limit_str));
        }
        self.get("/fapi/v3/markPriceKlines", &params).await
    }

    /// Get mark price and funding rate for a symbol (or all symbols if None).
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_mark_price(
        &self,
        symbol: Option<&str>,
    ) -> Result<ApiResponse<MarkPriceShape>, AsterDexError> {
        let mut params: Vec<(&str, &str)> = vec![];
        if let Some(s) = symbol {
            params.push(("symbol", s));
        }
        self.get("/fapi/v3/premiumIndex", &params).await
    }

    /// Get funding rate history for a symbol.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_funding_rate(
        &self,
        symbol: Option<&str>,
        start_time: Option<u64>,
        end_time: Option<u64>,
        limit: Option<u32>,
    ) -> Result<ApiResponse<Vec<FundingRateRecord>>, AsterDexError> {
        let start_time_str;
        let end_time_str;
        let limit_str;
        let mut params: Vec<(&str, &str)> = vec![];
        if let Some(s) = symbol {
            params.push(("symbol", s));
        }
        if let Some(st) = start_time {
            start_time_str = st.to_string();
            params.push(("startTime", &start_time_str));
        }
        if let Some(et) = end_time {
            end_time_str = et.to_string();
            params.push(("endTime", &end_time_str));
        }
        if let Some(l) = limit {
            limit_str = l.to_string();
            params.push(("limit", &limit_str));
        }
        self.get("/fapi/v3/fundingRate", &params).await
    }

    /// Get funding rate information for all symbols.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_funding_info(&self) -> Result<ApiResponse<Vec<FundingInfoResponse>>, AsterDexError> {
        self.get("/fapi/v3/fundingInfo", &[]).await
    }

    /// Get 24-hour ticker price change statistics.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_ticker_24hr(
        &self,
        symbol: Option<&str>,
    ) -> Result<ApiResponse<Ticker24hrShape>, AsterDexError> {
        let mut params: Vec<(&str, &str)> = vec![];
        if let Some(s) = symbol {
            params.push(("symbol", s));
        }
        self.get("/fapi/v3/ticker/24hr", &params).await
    }

    /// Get latest price for a symbol or all symbols.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_ticker_price(
        &self,
        symbol: Option<&str>,
    ) -> Result<ApiResponse<TickerPriceShape>, AsterDexError> {
        let mut params: Vec<(&str, &str)> = vec![];
        if let Some(s) = symbol {
            params.push(("symbol", s));
        }
        self.get("/fapi/v3/ticker/price", &params).await
    }

    /// Get best price/quantity on the order book for a symbol.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_book_ticker(
        &self,
        symbol: Option<&str>,
    ) -> Result<ApiResponse<BookTickerShape>, AsterDexError> {
        let mut params: Vec<(&str, &str)> = vec![];
        if let Some(s) = symbol {
            params.push(("symbol", s));
        }
        self.get("/fapi/v3/ticker/bookTicker", &params).await
    }

    /// Get index price references for a symbol.
    ///
    /// Public endpoint — no authentication required.
    pub async fn get_index_references(
        &self,
        symbol: Option<&str>,
    ) -> Result<ApiResponse<serde_json::Value>, AsterDexError> {
        let mut params: Vec<(&str, &str)> = vec![];
        if let Some(s) = symbol {
            params.push(("symbol", s));
        }
        self.get("/fapi/v3/indexreferences", &params).await
    }
}

// -------------------------------------------------------------------------
// US-007: Unit tests (mockito)
// -------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rest::client::RestClient;

    /// Test 1: ping returns Ok
    #[tokio::test]
    async fn ping_returns_ok() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/fapi/v3/ping")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body("{}")
            .create_async()
            .await;
        let client = RestClient::new_public(&server.url()).unwrap();
        let resp = client.ping().await.unwrap();
        let _ = resp.data; // PingResponse is empty struct — just assert Ok
    }

    /// Test 2: get_depth returns bids and asks
    #[tokio::test]
    async fn get_depth_returns_bids_asks() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/fapi/v3/depth")
            .match_query(mockito::Matcher::AllOf(vec![
                mockito::Matcher::UrlEncoded("symbol".to_string(), "BTCUSDT".to_string()),
                mockito::Matcher::UrlEncoded("limit".to_string(), "20".to_string()),
            ]))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"lastUpdateId":12345,"bids":[["45000.00","1.5"]],"asks":[["45001.00","0.5"]]}"#)
            .create_async()
            .await;
        let client = RestClient::new_public(&server.url()).unwrap();
        let resp = client.get_depth("BTCUSDT", Some(20)).await.unwrap();
        assert_eq!(resp.data.last_update_id, 12345);
        assert!(!resp.data.bids.is_empty());
        assert!(!resp.data.asks.is_empty());
    }

    /// Test 3: get_klines returns OHLCV data
    #[tokio::test]
    async fn get_klines_returns_ohlcv() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/fapi/v3/klines")
            .match_query(mockito::Matcher::AllOf(vec![
                mockito::Matcher::UrlEncoded("symbol".to_string(), "BTCUSDT".to_string()),
                mockito::Matcher::UrlEncoded("interval".to_string(), "1m".to_string()),
                mockito::Matcher::UrlEncoded("limit".to_string(), "1".to_string()),
            ]))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"[[1700000000000,"45000","46000","44000","45500","100.5",1700000059999,"4550000",500,"50.5","2275000"]]"#)
            .create_async()
            .await;
        let client = RestClient::new_public(&server.url()).unwrap();
        let resp = client
            .get_klines("BTCUSDT", KlineInterval::OneMinute, None, None, Some(1))
            .await
            .unwrap();
        assert_eq!(resp.data[0].open_time, 1_700_000_000_000u64);
    }

    /// Test 4: get_ticker_24hr returns JSON response
    #[tokio::test]
    async fn get_ticker_24hr_returns_json() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/fapi/v3/ticker/24hr")
            .match_query(mockito::Matcher::UrlEncoded(
                "symbol".to_string(),
                "BTCUSDT".to_string(),
            ))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"symbol":"BTCUSDT","lastPrice":"45000.00","priceChange":"100.00","priceChangePercent":"0.22","weightedAvgPrice":"44950.00","prevClosePrice":"44900.00","lastQty":"1.0","openPrice":"44900.00","highPrice":"46000.00","lowPrice":"44500.00","volume":"5000.0","quoteVolume":"224750000.0","openTime":1699999200000,"closeTime":1700085600000,"firstId":1,"lastId":5000,"count":5000}"#)
            .create_async()
            .await;
        let client = RestClient::new_public(&server.url()).unwrap();
        let resp = client.get_ticker_24hr(Some("BTCUSDT")).await;
        assert!(resp.is_ok());
    }

    /// Test 5: public endpoint does NOT include auth params in request URL.
    ///
    /// Strategy: mock matches EXACT query "symbol=BTCUSDT" (no auth fields).
    /// If auth params were injected the mock would not match and the call would fail.
    #[tokio::test]
    async fn public_endpoint_no_auth_params() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/fapi/v3/depth")
            .match_query(mockito::Matcher::UrlEncoded(
                "symbol".to_string(),
                "BTCUSDT".to_string(),
            ))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"lastUpdateId":1,"bids":[],"asks":[]}"#)
            .create_async()
            .await;
        let client = RestClient::new_public(&server.url()).unwrap();
        // If the client were injecting auth params (user=, signer=, nonce=, signature=)
        // the mock would NOT match (wrong query string) and the call would return an error.
        let result = client.get_depth("BTCUSDT", None).await;
        assert!(
            result.is_ok(),
            "Expected Ok but got error — auth params may have been injected: {:?}",
            result
        );
    }
}