The Coinbase Pro Client for Rust is a robust library that facilitates interaction with the Coinbase Pro API. It supports synchronous (sync), asynchronous (async), and websocket-feed data operations, making it versatile for various application needs.
To get started, add the following dependency to your Cargo.toml
:
[dependencies]
coinbase-pro-rs = "0.7.1"
Using the asynchronous client with hyper and tokio:
use hyper::rt::Future;
use coinbase_pro_rs::{Public, ASync, SANDBOX_URL};
fn main() {
let client: Public<ASync> = Public::new_with_keep_alive(SANDBOX_URL, false);
// If keep_alive is not disabled - tokio::run will hold the connection without exiting the example
let f = client.get_time()
.map_err(|_| ())
.and_then(|time| {
println!("Coinbase.time: {}", time.iso);
Ok(())
});
tokio::run(f); // waiting for tokio
}
Using the synchronous client:
use coinbase_pro_rs::{Public, Sync, SANDBOX_URL};
fn main() {
let client: Public<Sync> = Public::new(SANDBOX_URL);
let time = client.get_time().unwrap();
println!("Coinbase.time: {}", time.iso);
}
Streaming data through the websocket feed:
use futures::{Future, Stream};
use coinbase_pro_rs::{WSFeed, WS_SANDBOX_URL};
use coinbase_pro_rs::structs::wsfeed::*;
fn main() {
let stream = WSFeed::connect(WS_SANDBOX_URL, &["BTC-USD"], &[ChannelType::Heartbeat])
.await
.unwrap();
let f = stream
.take(10)
.for_each(|msg| {
match msg {
Message::Heartbeat {sequence, last_trade_id, time, ..} => println!("{}: seq:{} id{}",
time, sequence, last_trade_id),
Message::Error {message} => println!("Error: {}", message),
Message::InternalError(_) => panic!("internal_error"),
other => println!("{:?}", other)
}
Ok(())
});
tokio::run(f.map_err(|_| panic!("stream fail")));
}
The Coinbase Pro Client for Rust is designed to simplify the integration with Coinbase Pro, providing developers with the tools to efficiently access and manage cryptocurrency data and transactions.