Sample code for 30+ languages & platforms
Rust

WebSocket Binance Trade Stream (subscribe and receive updates)

See more WebSocket Examples

Subscribe to a binance trade stream and receive updates.

Chilkat Rust Downloads

Rust

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

let ws = chilkat::WebSocket::new();

// For brevity, this example does not check for errors when etablishing the WebSocket connection.
// See Establish WebSocket Connection for more complete sample code for making the connection.

let rest = chilkat::Rest::new();

// Connect to wss://stream.binance.com:9443
if rest.connect("stream.binance.com", 9443, true, false).is_err() {
    println!("{}", rest.last_error_text());
    return;
}

if ws.use_connection(&rest).is_err() {
    println!("{}", ws.last_error_text());
    return;
}

let _ = ws.add_client_headers();

//  Raw streams are accessed at /ws/<streamName>
let Ok(response_body) = rest.full_request_no_body("GET", "/ws/btcusdt") else {
    println!("{}", rest.last_error_text());
    return;
};

if ws.validate_server_handshake().is_err() {
    println!("{}", ws.last_error_text());
    println!("{}", response_body);
    println!("{}", rest.response_header());
    return;
}

println!("{}", response_body);
println!("{}", rest.response_header());

// POST JSON to subscribe to a stream

// {
// "method": "SUBSCRIBE",
// "params":
// [
// "btcusdt@aggTrade",
// "btcusdt@depth"
// ],
// "id": 1
// }

let json = chilkat::JsonObject::new();
let _ = json.update_string("method", "SUBSCRIBE");
let _ = json.update_string("params[0]", "btcusdt@aggTrade");
let _ = json.update_string("params[1]", "btcusdt@depth");
let _ = json.update_int("id", 1);

// Send a full message in a single frame
let final_frame = true;
if ws.send_frame(&json.emit().unwrap_or_default(), final_frame).is_err() {
    println!("{}", ws.last_error_text());
    return;
}

let json_trade_data = chilkat::JsonObject::new();
json_trade_data.set_emit_compact(false);

// Begin reading the trade stream response.
// We'll just read the 1st 10 updates and then exit..
let mut num_trades_received = 0;
while num_trades_received < 5 {

    if ws.read_frame().is_err() {
        println!("Failed to receive a frame");
        println!("ReadFrame fail reason = {}", ws.read_frame_fail_reason());
        println!("{}", ws.last_error_text());
        return;
    }

    // The responses we desire are in Text frames, where the opcode = 1.
    if ws.frame_opcode_int() == 1 {
        let received_json = ws.get_frame_data().unwrap_or_default();

        let _ = json_trade_data.load(&received_json);
        println!("{}", json_trade_data.emit().unwrap_or_default());

        num_trades_received = num_trades_received + 1;
    }

}

// Close the websocket connection.
if ws.send_close(true, 1000, "Closing this websocket.").is_err() {
    println!("{}", ws.last_error_text());
    return;
}

// Read the Close response.
if ws.read_frame().is_err() {
    println!("ReadFrame fail reason = {}", ws.read_frame_fail_reason());
    println!("{}", ws.last_error_text());
    return;
}

println!("Success.");

// The output of the above code is shown here: