Rust API connector for Bybit's WebSockets APIs.

Related tags

WebSocket rust-bybit
Overview

rust-bybit

English | 简体中文

Unofficial Rust API connector for Bybit's WebSockets APIs.

Disclaimer

This is an unofficial Rust API connector for Bybit's APIs and the user assumes all responsibility and risk for the use of this project.

Installation

Add this to Cargo.toml

[dependencies]
rust-bybit = { git = "https://github.com/yufuquant/rust-bybit.git" }

Basic Usage

Create a WebSocket client for specific topics:

use bybit::spot::ws::{PublicResponse, PublicWebSocketApiClient};

let mut client = PublicWebSocketApiClient::new("wss://stream.bybit.com/spot/quote/ws/v1");

Subscribe to topics you are interested in. The following code will subscribe to all topics with symbol=BTCUSDT and binary=false (for all available topics, check Bybit APIs documentation). Note that the subscriptions will not be sent until client.run is called:

client.subscribe_trade("BTCUSDT", false);
client.subscribe_realtimes("BTCUSDT", false);
client.subscribe_kline("BTCUSDT", "1m", false);
client.subscribe_depth("BTCUSDT", false);
client.subscribe_merged_depth("BTCUSDT", false, 1);
client.subscribe_diff_depth("BTCUSDT", false);
client.subscribe_lt("BTC3LUSDTNAV", false);

Pass a callback to client.run to start the client. The callback must accept exactly one parameter: the Enum which variants are WebSocket responses. The callback will be called whenever a WebSocket response is received:

let callback = |res: PublicResponse| match res {
    PublicResponse::Trade(res) => println!("Trade: {:?}", res),
    PublicResponse::Realtimes(res) => println!("Realtimes: {:?}", res),
    PublicResponse::Kline(res) => println!("Kline: {:?}", res),
    PublicResponse::Depth(res) => println!("Depth: {:?}", res),
    PublicResponse::MergedDepth(res) => println!("Merged depth: {:?}", res),
    PublicResponse::DiffDepth(res) => println!("Diff depth: {:?}", res),
    PublicResponse::LT(res) => println!("LT: {:?}", res),
    PublicResponse::Pong(res) => println!("Pong: {:?}", res),
    PublicResponse::Ping(res) => println!("Ping: {:?}", res),
};

match client.run(callback) {
    Ok(_) => {}
    Err(e) => println!("{}", e),
}

This is a simple example to just print the received WebSocket responses. There are some more complex examples for real usage demonstration, such as maintaining a local order book by subscribing diffDepth topic. You can run cargo run --example spot_local_order_book to see how it works.

Donate

You can donate to following cryptocurrency wallet addresses to help this project going further.

Network Address
Ethereum (ERC20) 0x2ef22ed84D6b57496dbb95257C4eb8F02cE9b7A6
BNB Smart Chain (BEP20) 0x869F8F9A78a18818F93061A02B233507b5F64151
Tron (TRC20) TPvqJYHFQ7iqEgtEcYrSLTjpGsAq41dhFt
Bitcoin 3C6o4ADGFXyuf6TUXKL6YyMyRfhek6zxzx
You might also like...
Websocket generic library for Bitwyre WS-API

Websocket Core (Rust) Websocket generic server library for: Periodic message broadcast Eventual (Pubsub) message broadcast Async request reply Authors

SockJS server for rust language

SockJS server SockJS server for Actix framework. API Documentation Cargo package: sockjs SockJS is built with Actix web Minimum supported Rust version

A WebSocket (RFC6455) library written in Rust

Rust-WebSocket Note: Maintainership of this project is slugglish. You may want to use tungstenite or tokio-tungstenite instead. Rust-WebSocket is a We

Lightweight stream-based WebSocket implementation for Rust.

Tungstenite Lightweight stream-based WebSocket implementation for Rust. use std::net::TcpListener; use std::thread::spawn; use tungstenite::server::ac

A very-very simple url shortener for Rust

urlshortener-rs A very simple urlshortener for Rust. This library aims to implement as much URL shortener services as possible and to provide an inter

A WebSocket (RFC6455) library written in Rust

Rust-WebSocket Rust-WebSocket is a WebSocket (RFC6455) library written in Rust. Rust-WebSocket provides a framework for dealing with WebSocket connect

An aria2 websocket jsonrpc in Rust.

aria2-ws An aria2 websocket jsonrpc in Rust. Built with tokio. Docs.rs aria2 RPC docs Features Almost all methods and structed responses Auto reconnec

A simple toy websocket client to connect to Bitstamp.net and print the live order book written in Rust.

A simple toy websocket client to connect to Bitstamp.net and print the live order book written in Rust.

RuTTY - Rust TTY Server
RuTTY - Rust TTY Server

RuTTY - Rust TTY Server Demo RuTTY (aka Ruthie) is a CLI-powered websocket server written in Rust that allows you to expose your commands via browser.

Comments
  • RFC: refactoring the inverse websocket for ergonomic use

    RFC: refactoring the inverse websocket for ergonomic use

    This PR is based on #6 and #7

    Hi! I'm opening this PR as a draft so I can get some early feedback; I've started taking the inverse websocket in a different direction than the spot/linear implementations and wanted to sync with you on this before it went too far off in the weeds. I'm not sure if some of these changes uphold the goals or direction you want to take this project, so I thought I'd ask!

    I started consuming the inverse websocket library from an application I'm writing and these changes were helpful in keeping the consuming code readable and fun:

    • exporting the type of an enum variant (I'm not sure if these words make sense, hopefully I'm close) This allows me to write a function expecting data from a particular response message

        pub fn initialize_from_snapshot(&mut self, snapshot_message: &OrderBookL2SnapshotMessage) {
            for rung in snapshot_message.data.iter() {
                self.insert_bybit_rung(rung);
            }
        }
      

      Well... now that I say this, I should probably just pass &Vec<OrderBookItem> and &OrderBookDelta (both already exported). Maybe this case is no longer as important to support, but it did bring the next point to my attention

    • create a distinction between the response or message and the contained data For example, we had

      pub struct BaseResponse<'a, D> {
          pub topic: &'a str,
          pub data: D,
      }
      
      pub enum PublicResponse<'a> {
          #[serde(borrow)]
          Trade(BaseResponse<Vec<Trade>>),
          // ...
      }
      

      This naturally had me thinking of the entire BaseResponse<Vec<Trade>> as a Trade (the enum variant) which caused a bit of a jerk when I accessed the data which was a ... Trade. It seemed more natural to refer to the unedited response as a TradeMessage which contains a Vec<Trade>. This rename causes the callback to be a little more verbose but seems to increase clarity everywhere else.

    • deserializing some raw websocket values into a different type This is the most questionable change, because if the project goal is to be as fast as possible, this may perform more work than is necessary in all cases. Also, there can be some precision issues when changing a string-of-a-number into a f64, but I'm not sure of any other, superior way of dealing with floats in Rust so I figure this conversion is sort of inevitable.

      Rather than handling these conversions on the client's side, I moved this logic into the deserializer using a crate called serde-aux. I've started to deserialize Side into an enum as well, which makes the client's logic cleaner and lets me lean on the type system more.

    • adding tests, currently only of deserialization logic I'm always a bit confused reading the serde documentation, so I wrote tests to prove the deserialization would work as I expected it to. I'm not sure yet how to test every part of this implementation but I'm excited to keep pushing for higher test coverage

    That's about it, so I guess my goals for these diffs are

    • leverage the type system to increase confidence about correctness and improve developer experience through "implementation by cases"
    • provide a great developer experience by presenting information from Bybit's API in a way that minimizes wtfs-per-minute (Bybit leaves a lot of room for improvement here)

    Thanks in advance!

    opened by EricCrosson 2
  • docs: Describe project goals

    docs: Describe project goals

    Following a conversation here, this commit tries to document project goals. We can use these goals as a compass to decide which changes are in scope and which are out of scope.

    Currently, this project is meant to be a lightweight layer for interacting with Bybit's WebSocket API. Performance is king, and this means many conveniences may have to be built into separate packages that build upon this package.

    This should make it easier to bring this project into a "complete" state.

    opened by EricCrosson 1
Owner
yufuquant
yufuquant
Synchronized state machines for Rust over WebSockets.

Aper is a framework for real-time sharing of application state over WebSockets.

null 191 Dec 20, 2022
Rust + wasm + websockets

This is a template repo for eframe, a framework for writing apps using egui.

Emil Ernerfeldt 12 Oct 3, 2022
Composable WebSockets made easy, for Rust 🦀

ezsockets Have you ever struggle with creating a WebSocket server or a client in Rust? This crate is for you. High level abstraction of WebSocket, han

Grzegorz Baranski 55 Dec 30, 2022
A MITM Proxy Written in Rust 🦀! Toolkit for HTTP/1, HTTP/2, and WebSockets with SSL/TLS Capabilities. Learning Project.

Man In The Middle Proxy Description Rust-based Man in the Middle proxy, an early-stage project aimed at providing visibility into network traffic. Cur

null 158 Mar 9, 2023
Command-line client for WebSockets, like netcat (or curl) for ws:// with advanced socat-like functions

websocat Netcat, curl and socat for WebSockets. Examples Connect to public echo server $ websocat ws://echo.websocket.org 123 123 ABC ABC Serve and c

Vitaly Shukela 5k Jan 4, 2023
Clearly a repo about websockets and their comparison...

Tags Go vs Typescript: Video 1 of the series is tag go-vs-ts-video-1 Current Project Video 2 and 3 are going to be likely Go vs Rust vs Typescript, bu

ThePrimeagen 344 Dec 31, 2022
😎 A custom invoke system for Tauri that leverages WebSockets

?? tauri-awesome-rpc This is a crate provides a custom invoke system for Tauri using a localhost JSON RPC WebSocket. Each message is delivered through

Victor Aremu 20 Dec 2, 2022
A command-line tool for exposing a wrapped program's standard IO using WebSockets/SSE

cmdpiped cmdpiped is a command-line tool for exposing a wrapped cli program's standard IO to WebSockets/SSE Installation Ready to use Binaries are ava

Geoffrey Mureithi 10 Nov 11, 2022
notiflux - subscribe over WebSockets, publish over REST

notiflux notiflux is a pub/sub server where clients subscribe over a WebSocket and messages are broadcast over a POST request How does it work? Client

Axel Örn Sigurðsson 3 Apr 9, 2024
A CLI development tool for WebSocket APIs

A CLI development tool for WebSocket APIs

Espen Henriksen 622 Dec 26, 2022