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...
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.

Easy c̵̰͠r̵̛̠ö̴̪s̶̩̒s̵̭̀-t̶̲͝h̶̯̚r̵̺͐e̷̖̽ḁ̴̍d̶̖̔ ȓ̵͙ė̶͎ḟ̴͙e̸̖͛r̶̖͗ë̶̱́ṉ̵̒ĉ̷̥e̷͚̍ s̷̹͌h̷̲̉a̵̭͋r̷̫̊ḭ̵̊n̷̬͂g̵̦̃ f̶̻̊ơ̵̜ṟ̸̈́ R̵̞̋ù̵̺s̷̖̅ţ̸͗!̸̼͋

Rust S̵̓i̸̓n̵̉ I̴n̴f̶e̸r̵n̷a̴l mutability! Howdy, friendly Rust developer! Ever had a value get m̵̯̅ð̶͊v̴̮̾ê̴̼͘d away right under your nose just when

🛂Rust implementation of lavaplayer connector

🛂 mixtape-bot/connector-rs Rust implementation of lavaplayer connector Discord Server Original Implementation 📦 Progress Since I'm basically a compl

A temporary repo for ETH connector to be used by EVM

ETH connector for Rainbow bridge Definitions bridgedETH - NEP-141 fungible-token representation of ETH inside Near. nETH - native ETH inside Near EVM.

Lightweight, event-driven WebSockets for Rust.

WS-RS Lightweight, event-driven WebSockets for Rust. /// A WebSocket echo server listen("127.0.0.1:3012", |out| { move |msg| { out.send(ms

Synchronized state machines for Rust over WebSockets.

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

Autogenerated async RPC bindings that instantly connect a JS frontend to a Rust backend service via WebSockets and WASM.

Turbocharger Autogenerated async RPC bindings that instantly connect a JS frontend to a Rust backend service via WebSockets and WASM. See https://gith

Rust + wasm + websockets

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

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

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

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

Plutonium is a two-device chat application that utilises WebSockets and a X25519 ECDH Key Exchange

Plutonium is a two-device chat application that utilises WebSockets and a X25519 ECDH Key Exchange, in addition to AES-256 to securely communicate between the two clients.

😎 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

A simple web server(and library) to display server stats over HTTP and Websockets/SSE or stream it to other systems.

x-server-stats A simple web server(and library) to display server stats over HTTP and Websockets/SSE or stream it to other systems. x-server(in x-serv

libhdfs binding and wrapper APIs for Rust

hdfs-rs libhdfs binding library and rust APIs which safely wraps libhdfs binding APIs Current Status Alpha Status (Rust wrapping APIs can be changed)

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
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 CLI development tool for WebSocket APIs

A CLI development tool for WebSocket APIs

Espen Henriksen 622 Dec 26, 2022
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

Bitwyre 13 Oct 28, 2022
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

Actix 63 Oct 7, 2022
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

Rust Websockets 1.3k Jan 6, 2023