maxt 0.2.1

One Rust API for Upbit, Bithumb, Binance, and Hyperliquid market data, accounts, and orders.
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
//! The streams returned by live subscriptions.

use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

use futures_core::Stream;

use crate::error::Result;
use crate::types::{AccountEvent, MarketEvent};

type CloseFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
type CloseHook = Box<dyn FnOnce() -> CloseFuture + Send + 'static>;

fn poll_stream<T>(
    inner: &mut Option<Pin<Box<dyn Stream<Item = Result<T>> + Send>>>,
    close: &mut Option<CloseHook>,
    closing: &mut Option<CloseFuture>,
    cx: &mut Context<'_>,
) -> Poll<Option<Result<T>>> {
    if closing.is_none() {
        match inner.as_mut() {
            Some(source) => match source.as_mut().poll_next(cx) {
                Poll::Ready(None) => {
                    inner.take();
                    *closing = close.take().map(|close| close());
                }
                polled => return polled,
            },
            None => return Poll::Ready(None),
        }
    }

    let Some(cleanup) = closing.as_mut() else {
        return Poll::Ready(None);
    };
    match cleanup.as_mut().poll(cx) {
        Poll::Pending => Poll::Pending,
        Poll::Ready(result) => {
            *closing = None;
            inner.take();
            match result {
                Ok(()) => Poll::Ready(None),
                Err(error) => Poll::Ready(Some(Err(error))),
            }
        }
    }
}

/// A live market data subscription.
///
/// Yields [`MarketEvent`]s until it ends with `None`. Built-in adapters handle
/// reconnects and emit [`MarketEvent::Reconnected`]; custom producers define
/// their own reconnect behavior.
///
/// An `Err` item reports a failed frame or connection operation but does not by
/// itself end the stream. Consumers may continue polling after it.
///
/// `None` is the termination signal. It can follow exhaustion of
/// [`StreamConfig::max_reconnect_attempts`](crate::StreamConfig::max_reconnect_attempts).
/// Under [`Overflow::DropNewest`](crate::Overflow::DropNewest), the final error
/// may be dropped when the buffer is full, so consumers must also handle `None`
/// without a preceding error.
///
/// Dropping this value drops its inner stream. The built-in adapters use that
/// signal to stop their connection tasks; a custom stream controls its own
/// cleanup.
pub struct MarketStream {
    inner: Option<Pin<Box<dyn Stream<Item = Result<MarketEvent>> + Send>>>,
    close: Option<CloseHook>,
    closing: Option<CloseFuture>,
}

impl MarketStream {
    /// Wraps an adapter's own event source as a `MarketStream`.
    ///
    /// The only way to build one, so an [`Adapter`](crate::Adapter) written
    /// outside this crate needs it to return from
    /// [`Adapter::subscribe`](crate::Adapter::subscribe).
    ///
    /// The inner stream is polled unchanged. Its producer handles reconnects
    /// and emits [`MarketEvent::Reconnected`].
    pub fn new(inner: impl Stream<Item = Result<MarketEvent>> + Send + 'static) -> Self {
        Self {
            inner: Some(Box::pin(inner)),
            close: None,
            closing: None,
        }
    }

    /// Wraps an event source with cleanup that natural exhaustion and explicit
    /// [`Self::close`] await.
    ///
    /// Dropping the stream still drops `inner` immediately. Use `close` when the
    /// producer must confirm asynchronous cleanup, such as a foreign runtime
    /// cancelling its subscription task.
    pub fn new_with_close<F, Fut>(
        inner: impl Stream<Item = Result<MarketEvent>> + Send + 'static,
        close: F,
    ) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        Self {
            inner: Some(Box::pin(inner)),
            close: Some(Box::new(move || Box::pin(close()))),
            closing: None,
        }
    }

    /// Stops this stream and waits for adapter-provided asynchronous cleanup.
    ///
    /// The source is dropped even when cleanup returns an error. Repeated calls
    /// are no-ops. If the caller cancels this future, the next call resumes the
    /// same cleanup future.
    pub async fn close(&mut self) -> Result<()> {
        if self.closing.is_none() {
            self.closing = self.close.take().map(|close| close());
        }
        let result = match self.closing.as_mut() {
            Some(closing) => closing.await,
            None => Ok(()),
        };
        self.closing = None;
        self.inner.take();
        result
    }
}

impl Stream for MarketStream {
    type Item = Result<MarketEvent>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.as_mut().get_mut();
        poll_stream(&mut this.inner, &mut this.close, &mut this.closing, cx)
    }
}

impl fmt::Debug for MarketStream {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MarketStream").finish_non_exhaustive()
    }
}

/// A live private account subscription.
///
/// Yields [`AccountEvent`]s until it ends with `None`. Built-in adapters handle
/// reconnects and emit [`AccountEvent::Reconnected`]; custom producers define
/// their own reconnect behavior.
///
/// An `Err` item is a report, not the end, exactly as on [`MarketStream`].
/// Errors may include frame decoding, reconnect failures, and credential
/// renewal failures. `None` has the same termination semantics as
/// [`MarketStream`]. Dropping this value drops its inner stream; cleanup is the
/// producer's responsibility.
pub struct AccountStream {
    inner: Option<Pin<Box<dyn Stream<Item = Result<AccountEvent>> + Send>>>,
    close: Option<CloseHook>,
    closing: Option<CloseFuture>,
}

impl AccountStream {
    /// Wraps an adapter's own event source as an `AccountStream`.
    ///
    /// The only way to build one, so an [`Adapter`](crate::Adapter) written
    /// outside this crate needs it to return from
    /// [`Adapter::subscribe_account`](crate::Adapter::subscribe_account).
    ///
    /// The inner stream is polled unchanged. Its producer handles reconnects,
    /// emits [`AccountEvent::Reconnected`], and reports credential-renewal
    /// failures as `Err` items.
    pub fn new(inner: impl Stream<Item = Result<AccountEvent>> + Send + 'static) -> Self {
        Self {
            inner: Some(Box::pin(inner)),
            close: None,
            closing: None,
        }
    }

    /// Wraps an event source with cleanup that natural exhaustion and explicit
    /// [`Self::close`] await.
    ///
    /// Dropping the stream still drops `inner` immediately. Use `close` when the
    /// producer must confirm asynchronous cleanup, such as a foreign runtime
    /// cancelling its subscription task.
    pub fn new_with_close<F, Fut>(
        inner: impl Stream<Item = Result<AccountEvent>> + Send + 'static,
        close: F,
    ) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        Self {
            inner: Some(Box::pin(inner)),
            close: Some(Box::new(move || Box::pin(close()))),
            closing: None,
        }
    }

    /// Stops this stream and waits for adapter-provided asynchronous cleanup.
    ///
    /// The source is dropped even when cleanup returns an error. Repeated calls
    /// are no-ops. If the caller cancels this future, the next call resumes the
    /// same cleanup future.
    pub async fn close(&mut self) -> Result<()> {
        if self.closing.is_none() {
            self.closing = self.close.take().map(|close| close());
        }
        let result = match self.closing.as_mut() {
            Some(closing) => closing.await,
            None => Ok(()),
        };
        self.closing = None;
        self.inner.take();
        result
    }
}

impl Stream for AccountStream {
    type Item = Result<AccountEvent>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.as_mut().get_mut();
        poll_stream(&mut this.inner, &mut this.close, &mut this.closing, cx)
    }
}

impl fmt::Debug for AccountStream {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AccountStream").finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

    use super::*;
    use futures_util::StreamExt;
    use futures_util::stream;

    struct PendingUntilDrop(Arc<AtomicBool>);

    impl futures_core::Stream for PendingUntilDrop {
        type Item = Result<MarketEvent>;

        fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            Poll::Pending
        }
    }

    impl Drop for PendingUntilDrop {
        fn drop(&mut self) {
            self.0.store(true, Ordering::SeqCst);
        }
    }

    struct CompletesThenDrops<T>(Arc<AtomicBool>, std::marker::PhantomData<T>);

    impl<T> futures_core::Stream for CompletesThenDrops<T> {
        type Item = T;

        fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            Poll::Ready(None)
        }
    }

    impl<T> Drop for CompletesThenDrops<T> {
        fn drop(&mut self) {
            self.0.store(true, Ordering::SeqCst);
        }
    }

    #[tokio::test]
    async fn natural_completion_drops_market_and_account_sources_immediately() {
        let market_dropped = Arc::new(AtomicBool::new(false));
        let account_dropped = Arc::new(AtomicBool::new(false));
        let mut market = MarketStream::new(CompletesThenDrops(
            Arc::clone(&market_dropped),
            std::marker::PhantomData,
        ));
        let mut account = AccountStream::new(CompletesThenDrops(
            Arc::clone(&account_dropped),
            std::marker::PhantomData,
        ));

        assert!(market.next().await.is_none());
        assert!(account.next().await.is_none());
        assert!(market_dropped.load(Ordering::SeqCst));
        assert!(account_dropped.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn a_market_stream_yields_what_the_adapter_produced() {
        let events = vec![Ok(MarketEvent::Reconnected), Ok(MarketEvent::Reconnected)];
        let mut market_stream = MarketStream::new(stream::iter(events));

        assert!(matches!(
            market_stream.next().await,
            Some(Ok(MarketEvent::Reconnected))
        ));
        assert!(market_stream.next().await.is_some());
        assert!(market_stream.next().await.is_none());
    }

    #[tokio::test]
    async fn an_err_is_an_item_the_stream_polls_past_rather_than_its_end() {
        // The documented contract: only `None` ends a stream, so an error in
        // the middle must not swallow what comes after it.
        let events = vec![
            Err(crate::Error::decode("a frame that could not be read")),
            Ok(AccountEvent::Reconnected),
        ];
        let mut account_stream = AccountStream::new(stream::iter(events));

        assert!(matches!(account_stream.next().await, Some(Err(_))));
        assert!(matches!(
            account_stream.next().await,
            Some(Ok(AccountEvent::Reconnected))
        ));
        assert!(account_stream.next().await.is_none());
    }

    #[tokio::test]
    async fn explicit_close_awaits_the_hook_then_drops_the_source() {
        let dropped = Arc::new(AtomicBool::new(false));
        let hook_calls = Arc::new(AtomicUsize::new(0));
        let (release, released) = tokio::sync::oneshot::channel();
        let observed_calls = Arc::clone(&hook_calls);
        let mut stream = MarketStream::new_with_close(
            PendingUntilDrop(Arc::clone(&dropped)),
            move || async move {
                observed_calls.fetch_add(1, Ordering::SeqCst);
                let _ = released.await;
                Ok(())
            },
        );

        let close = tokio::spawn(async move {
            let result = stream.close().await;
            (stream, result)
        });
        while hook_calls.load(Ordering::SeqCst) == 0 {
            tokio::task::yield_now().await;
        }
        assert!(!dropped.load(Ordering::SeqCst));

        release.send(()).unwrap();
        let (mut stream, result) = close.await.unwrap();

        assert!(result.is_ok());
        assert!(dropped.load(Ordering::SeqCst));
        assert!(stream.next().await.is_none());
        assert!(stream.close().await.is_ok());
        assert_eq!(hook_calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn a_failed_close_hook_still_drops_the_account_source() {
        struct PendingAccount(Arc<AtomicBool>);

        impl futures_core::Stream for PendingAccount {
            type Item = Result<AccountEvent>;

            fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
                Poll::Pending
            }
        }

        impl Drop for PendingAccount {
            fn drop(&mut self) {
                self.0.store(true, Ordering::SeqCst);
            }
        }

        let dropped = Arc::new(AtomicBool::new(false));
        let mut stream =
            AccountStream::new_with_close(PendingAccount(Arc::clone(&dropped)), || async {
                Err(crate::Error::adapter("close failed"))
            });

        assert!(stream.close().await.is_err());
        assert!(dropped.load(Ordering::SeqCst));
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn a_cancelled_close_can_resume_the_same_cleanup_future() {
        let dropped = Arc::new(AtomicBool::new(false));
        let hook_calls = Arc::new(AtomicUsize::new(0));
        let (release, released) = tokio::sync::oneshot::channel();
        let observed_calls = Arc::clone(&hook_calls);
        let mut stream = MarketStream::new_with_close(
            PendingUntilDrop(Arc::clone(&dropped)),
            move || async move {
                observed_calls.fetch_add(1, Ordering::SeqCst);
                let _ = released.await;
                Ok(())
            },
        );

        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(10), stream.close())
                .await
                .is_err()
        );
        assert!(!dropped.load(Ordering::SeqCst));
        assert_eq!(hook_calls.load(Ordering::SeqCst), 1);

        release.send(()).unwrap();
        assert!(stream.close().await.is_ok());
        assert!(dropped.load(Ordering::SeqCst));
        assert_eq!(hook_calls.load(Ordering::SeqCst), 1);
    }
}