Saving data from tungstenite WebSocket client

I set up a WebSocket client to query a WebSocket Server and stream data every 1 second.

main.rs

use tungstenite::connect;
use url::Url;

mod models;

static BINANCE_WS_API: &str = "wss://stream.binance.com:9443";
fn main() {
    let binance_url = format!(
        "{}/stream?streams=ethbtc@depth5@1000ms/btcusdt@depth5@1000ms",
        BINANCE_WS_API
    );
    let (mut socket, response) =
        connect(Url::parse(&binance_url).unwrap()).expect("Can't connect.");

    println!("Connected to binance stream.");
    println!("HTTP status code: {}", response.status());
    println!("Response headers:");
    for (ref header, ref header_value) in response.headers() {
        println!("- {}: {:?}", header, header_value);
    }

    loop {
        let msg = socket.read_message().expect("Error reading message");
        let msg = match msg {
            tungstenite::Message::Text(s) => s,
            _ => {
                panic!("Error getting text");
            }
        };

        let parsed: models::BidAskWrapper = serde_json::from_str(&msg).expect("Can't parse");
        for i in 0..parsed.data.asks.len() {
            println!(
                "{}: {}. ask: {}, size: {}",
                parsed.stream, i, parsed.data.asks[i].price, parsed.data.asks[i].size
            );
        }
    }
}

models.rs

se serde::de;
use serde::{Deserialize, Deserializer};

#[derive(Debug, Deserialize)]
pub struct QueryData {
    #[serde(deserialize_with = "de_float_from_str")]
    pub price: f32,
    #[serde(deserialize_with = "de_float_from_str")]
    pub size: f32,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BidAskData {
    pub last_update_id: u128,
    pub bids: Vec<QueryData>,
    pub asks: Vec<QueryData>,
}

pub fn de_float_from_str<'a , D>(deserializer: D) -> Result<f32, D::Error>
where
    D: Deserializer<'a>,
{
    let str_val = String::deserialize(deserializer)?;
    str_val.parse::<f32>().map_err(de::Error::custom)
}

#[derive(Debug, Deserialize)]
pub struct BidAskWrapper {
    pub stream: String,
    pub data: BidAskData,
}

My goal is to save the data stream (to a database?) and perform operations on the data, e.g., tally the ask price every min and save (or return) the average ask price each minute.

I looked into the rusqlite crate, but had a difficult time modifying the example to work with my WebSocket client above.

What is the best way to save the data stream from the WebSocket client?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.