binance / binance-spot-connector-rust

MIT License
124 stars 43 forks source link

Subscribe on multiple BookTickerStream dynamically #9

Closed raeisimv closed 3 months ago

raeisimv commented 10 months ago

Subscribing to multiple symbols can be done as follows:

let mut conn = BinanceWebSocketClient::connect_with_url(&stream_adr)?;
conn.subscribe(vec![
    &BookTickerStream::from_symbol("BTCUSDT").into(),
    &BookTickerStream::from_symbol("BNBBUSD").into(),
]);

It works fine, however, I need to subscribe to a dynamic list of symbols (based on the app's settings).

let symbol_lst = vec!["BTCUSDT".to_string(), "BNBBUSD".to_string(), "BTCUSDT".to_string()];

let lst = symbol_lst.iter()
    .map(|x| BookTickerStream::from_symbol(&x))
    .collect::<Vec<_>>()
    ;

// try 1
conn.subscribe(lst.into_iter().map(|x| x.into()));
// ^^^^ the trait `From<BookTickerStream>` is not implemented for `&binance_spot_connector_rust::websocket::Stream`

// try 2
conn.subscribe(lst.into_iter().map(|x| &x.into()));
// returns a reference to data owned by the current function

Description

The issue comes from failing to convert BookTickerStream into stream (impl From<BookTickerStream> for Stream). There is no public API to create websocket::Stream, so it is required to use the converter.

stupid-boar commented 7 months ago

you can start the subscription sequentially as a temporary solution:

// let conn = Arc<Mutex<WebSocketState>>;
join_all(symbols.iter().map(|symbol| {
  let conn = conn.clone();
  async move {
    conn.lock().await.subscribe(vec![&TradeStream::new(&symbol).into()]).await
  }
})).await;
alplabin commented 3 months ago

It has been added in latest release: https://github.com/binance/binance-spot-connector-rust/releases/tag/v1.2.0