1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
use super::{
deserialize_response, deserialize_to_date, deserialize_to_f64, COINBASE_API_URL,
COINBASE_SANDBOX_API_URL,
};
use crate::error::Error;
use chrono::{DateTime, Utc};
use reqwest;
use serde;
pub struct PublicClient {
reqwest_client: reqwest::Client,
url: &'static str,
}
impl PublicClient {
pub fn new() -> Self {
Self {
reqwest_client: reqwest::Client::new(),
url: COINBASE_API_URL,
}
}
pub fn new_sandbox() -> Self {
Self {
reqwest_client: reqwest::Client::new(),
url: COINBASE_SANDBOX_API_URL,
}
}
async fn get<T>(&self, path: &str) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
let response = self
.reqwest_client
.get(format!("{}{}", self.url, path))
.header(reqwest::header::USER_AGENT, "coinbase_client")
.send()
.await?;
deserialize_response(response).await
}
pub async fn get_products(&self) -> Result<Vec<Product>, Error> {
let products: Vec<Product> = self.get("/products").await?;
Ok(products)
}
pub async fn get_product(&self, id: &str) -> Result<Product, Error> {
let product: Product = self.get(&format!("/products/{}", id)).await?;
Ok(product)
}
async fn get_order_book(
&self,
id: &str,
level: OrderLevel,
) -> Result<OrderBook<BookEntry>, Error> {
let book: OrderBook<BookEntry> = self
.get(&format!("/products/{}/book?level={}", id, level as u8))
.await?;
Ok(book)
}
pub async fn get_product_order_book(&self, id: &str) -> Result<OrderBook<BookEntry>, Error> {
Ok(self.get_order_book(id, OrderLevel::One).await?)
}
pub async fn get_product_order_book_top50(
&self,
id: &str,
) -> Result<OrderBook<BookEntry>, Error> {
Ok(self.get_order_book(id, OrderLevel::Two).await?)
}
pub async fn get_product_order_book_all(
&self,
id: &str,
) -> Result<OrderBook<FullBookEntry>, Error> {
let book: OrderBook<FullBookEntry> =
self.get(&format!("/products/{}/book?level=3", id)).await?;
Ok(book)
}
pub async fn get_product_ticker(&self, id: &str) -> Result<Ticker, Error> {
let ticker = self.get(&format!("/products/{}/ticker", id)).await?;
Ok(ticker)
}
pub async fn get_product_trades(
&self,
id: &str,
before_pagination_id: Option<u64>,
after_pagination_id: Option<u64>,
limit: Option<u16>,
) -> Result<Vec<Trade>, Error> {
let mut path = format!("/products/{}/trades", id);
let mut appended = false;
if let Some(n) = before_pagination_id {
appended = true;
path.push_str(&format!("?before={}", n))
}
if let Some(n) = after_pagination_id {
if appended {
path.push_str(&format!("&after={}", n))
} else {
appended = true;
path.push_str(&format!("?after={}", n))
}
}
if let Some(mut n) = limit {
if n > 1000 {
n = 1000;
}
if appended {
path.push_str(&format!("&limit={}", n))
} else {
path.push_str(&format!("?limit={}", n))
}
}
let trades: Vec<Trade> = self.get(&path).await?;
Ok(trades)
}
pub async fn get_product_historic_rates(
&self,
id: &str,
start: Option<&str>,
end: Option<&str>,
granularity: Option<Granularity>,
) -> Result<Vec<HistoricRate>, Error> {
let mut appended = false;
let mut path = format!("/products/{}/candles", id);
if let Some(n) = start {
appended = true;
path.push_str(&format!("?start={}", n));
}
if let Some(n) = end {
if appended {
path.push_str(&format!("&end={}", n));
} else {
path.push_str(&format!("?end={}", n));
}
}
if let Some(n) = granularity {
if appended {
path.push_str(&format!("&granularity={}", n as u32));
} else {
path.push_str(&format!("?granularity={}", n as u32));
}
}
let rates: Vec<HistoricRate> = self.get(&path).await?;
Ok(rates)
}
pub async fn get_product_24hr_stats(&self, id: &str) -> Result<TwentyFourHourStats, Error> {
let stats: TwentyFourHourStats = self.get(&format!("/products/{}/stats", id)).await?;
Ok(stats)
}
pub async fn get_currencies(&self) -> Result<Vec<Currency>, Error> {
let currencies: Vec<Currency> = self.get("/currencies").await?;
Ok(currencies)
}
pub async fn get_currency(&self, id: &str) -> Result<Currency, Error> {
let currency: Currency = self.get(&format!("/currencies/{}", id)).await?;
Ok(currency)
}
pub async fn get_time(&self) -> Result<Time, Error> {
let time: Time = self.get("/time").await?;
Ok(time)
}
}
#[derive(serde::Deserialize, Debug)]
pub struct Product {
pub id: String,
pub display_name: String,
pub base_currency: String,
pub quote_currency: String,
#[serde(deserialize_with = "deserialize_to_f64")]
pub base_increment: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub quote_increment: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub base_min_size: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub base_max_size: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub min_market_funds: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub max_market_funds: f64,
pub status: String,
pub status_message: String,
pub cancel_only: bool,
pub limit_only: bool,
pub post_only: bool,
pub trading_disabled: bool,
}
#[derive(serde::Deserialize, Debug)]
pub struct BookEntry {
#[serde(deserialize_with = "deserialize_to_f64")]
pub price: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub size: f64,
pub num_orders: u64,
}
#[derive(serde::Deserialize, Debug)]
pub struct FullBookEntry {
#[serde(deserialize_with = "deserialize_to_f64")]
pub price: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub size: f64,
pub order_id: String,
}
#[derive(serde::Deserialize, Debug)]
pub struct OrderBook<T> {
pub bids: Vec<T>,
pub asks: Vec<T>,
pub sequence: u64,
}
#[derive(serde::Deserialize, Debug)]
pub struct Trade {
#[serde(deserialize_with = "deserialize_to_date")]
pub time: DateTime<Utc>,
pub trade_id: u64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub price: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub size: f64,
pub side: String,
}
#[derive(serde::Deserialize, Debug)]
pub struct Ticker {
pub trade_id: u64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub price: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub size: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub bid: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub ask: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub volume: f64,
#[serde(deserialize_with = "deserialize_to_date")]
pub time: DateTime<Utc>,
}
#[derive(serde::Deserialize, Debug)]
pub struct HistoricRate {
pub time: f64,
pub low: f64,
pub high: f64,
pub open: f64,
pub close: f64,
pub volume: f64,
}
#[derive(serde::Deserialize, Debug)]
pub struct TwentyFourHourStats {
#[serde(deserialize_with = "deserialize_to_f64")]
pub open: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub high: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub low: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub volume: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub last: f64,
#[serde(deserialize_with = "deserialize_to_f64")]
pub volume_30day: f64,
}
#[derive(serde::Deserialize, Debug)]
pub struct Currency {
pub id: String,
pub name: String,
#[serde(deserialize_with = "deserialize_to_f64")]
pub min_size: f64,
pub status: String,
pub message: String,
#[serde(deserialize_with = "deserialize_to_f64")]
pub max_precision: f64,
pub convertible_to: Option<Vec<String>>,
pub details: CurrencyDetails,
}
#[derive(serde::Deserialize, Debug)]
pub struct CurrencyDetails {
pub r#type: String,
pub symbol: String,
pub network_confirmations: u64,
pub sort_order: u64,
pub crypto_address_link: String,
pub crypto_transaction_link: String,
pub push_payment_methods: Vec<String>,
pub group_types: Vec<String>,
pub display_name: Option<String>,
pub processing_time_seconds: Option<f64>,
pub min_withdrawal_amount: f64,
pub max_withdrawal_amount: f64,
}
#[derive(serde::Deserialize, Debug)]
pub struct Time {
#[serde(deserialize_with = "deserialize_to_date")]
pub iso: DateTime<Utc>,
pub epoch: f64,
}
enum OrderLevel {
One = 1,
Two = 2,
}
pub enum Granularity {
OneMinute = 60,
FiveMinutes = 300,
FifteenMinutes = 900,
OneHour = 3600,
SixHours = 21600,
OneDay = 86400,
}