robinrust 1.0.3

A lightweight, async Rust library for interacting with Robinhood's Crypto trading endpoints.
Documentation
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Trading-related endpoints for Robinhood crypto.
//!
//! This module exposes helpers to query trading pairs and holdings, list and
//! create crypto orders, and cancel existing orders. All functions rely on
//! authenticated requests built via the `auth` module.
use thiserror::Error;

use crate::auth::Robinhood;
use reqwest::Client;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use typed_builder::TypedBuilder;
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
/// Response containing available crypto trading pairs.
pub struct CryptoTradingPairsResponse{
    pub next: Option<String>,
    pub previous: Option<String>,
    pub results: Vec<TradingPairs>,
}

#[derive(Debug, Serialize, Deserialize)]
/// A tradable crypto pair (e.g., BTC-USD) with increments and size limits.
pub struct TradingPairs{
    pub asset_code: String,
    pub quote_code: String,
    pub quote_increment: String,
    pub asset_increment: String,
    pub max_order_size: String,
    pub min_order_size: String,
    pub status: String,
    pub symbol: String,
}

impl TradingPairs{
    /// Check if a quantity is within the allowed min/max order sizes for this pair.
    pub fn check_valid_trade(&self, quantity: Decimal) -> bool{
        let max_order_size = Decimal::from_str(&self.max_order_size).unwrap();
        let min_order_size = Decimal::from_str(&self.min_order_size).unwrap();
        quantity <= max_order_size && quantity >= min_order_size
    }
}

/// List supported crypto trading pairs, optionally filtered by symbol(s).
///
/// `symbols` should be values like "BTC-USD"; when empty, returns all pairs.
pub async fn get_crypto_trading_pairs(rh: &Robinhood, symbols: Vec<&str>) -> Result<CryptoTradingPairsResponse, reqwest::Error>{
    let mut path = String::from("/api/v1/crypto/trading/trading_pairs/");
    if !symbols.is_empty() {
        path.push('?');
        for (i, sym) in symbols.iter().enumerate() {
            if i > 0 {
                path.push('&');
            }
            // Consider URL-escaping sym if needed
            path.push_str("symbol=");
            path.push_str(sym);
        }
    }
    let headers = rh.auth_headers(&path, "GET", "");
    let client = Client::new();
    let resp = client
        .get(format!("https://trading.robinhood.com{path}"))
        .headers(headers)
        .send()
        .await?.json::<CryptoTradingPairsResponse>().await?;
    Ok(resp)
}

#[tokio::test]
async fn test_get_trading_pairs(){
    let rh = Robinhood::from_env();
    match get_crypto_trading_pairs(&rh, vec!["BTC-USD"]).await{
        Ok(resp) => {
            assert_eq!(resp.results[0].asset_code, "BTC");
            assert_eq!(resp.results[0].quote_code, "USD");
        }
        Err(e) => {
            panic!("Error with trading pairs: {}", e);
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
/// Response containing crypto holdings for the account.
pub struct CryptoHoldingsResponse{
    pub next: Option<String>,
    pub previous: Option<String>,
    pub results: Vec<CryptoHoldings>
}

#[derive(Debug, Serialize, Deserialize)]
/// A single crypto holding entry for the account.
pub struct CryptoHoldings{
    pub account_number: String,
    pub asset_code: String,
    #[serde(with = "rust_decimal::serde::float")]
    pub total_quantity: Decimal,
    #[serde(with = "rust_decimal::serde::float")]
    pub quantity_available_for_trading: Decimal,
}

/// Get holdings for the authenticated account, optionally filtering by asset code(s).
///
/// `symbols` contains asset codes like "BTC"; when empty, returns all holdings.
pub async fn get_crypto_holdings(rh: &Robinhood, symbols: Vec<&str>) -> Result<CryptoHoldingsResponse, reqwest::Error>{
    let mut path = String::from("/api/v1/crypto/trading/holdings/");
    if !symbols.is_empty() {
        path.push('?');
        for (i, sym) in symbols.iter().enumerate() {
            if i > 0 {
                path.push('&');
            }
            // Consider URL-escaping sym if needed
            path.push_str("asset_code=");
            path.push_str(sym);
        }
    }
    let headers = rh.auth_headers(&path, "GET", "");
    let client = Client::new();
    let resp = client
        .get(format!("https://trading.robinhood.com{path}"))
        .headers(headers)
        .send()
        .await?.json::<CryptoHoldingsResponse>().await?;
    Ok(resp)
}

#[tokio::test]
async fn test_get_crypto_holdings(){
    let rh = Robinhood::from_env();
    match get_crypto_holdings(&rh, vec!["BTC"]).await{
        Ok(resp) => {
            assert_eq!(resp.next, None);
        }
        Err(e) => {
            panic!("Error with crypto holdings: {}", e);
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
/// Paginated response for listing crypto orders.
pub struct CryptoOrdersResponse {
    pub next: Option<String>,
    pub previous: Option<String>,
    pub results: Vec<CryptoOrder>,
}

#[derive(Debug, Serialize, Deserialize)]
/// A crypto order as returned by Robinhood's trading API.
pub struct CryptoOrder {
    pub id: String,
    pub account_number: String,
    pub symbol: String,
    pub client_order_id: String,
    pub side: String,
    pub executions: Vec<Executions>,

    #[serde(rename = "type")]
    pub order_type: String,

    pub state: String,

    // May be absent or null
    #[serde(default, with = "rust_decimal::serde::str_option")]
    pub average_price: Option<Decimal>,

    // Always present (in your sample); string number
    #[serde(with = "rust_decimal::serde::str")]
    pub filled_asset_quantity: Decimal,

    pub created_at: String,
    pub updated_at: String,

    pub market_order_config: Option<MarketOrderConfig>,
    pub limit_order_config: Option<LimitOrderConfig>,
    pub stop_loss_order_config: Option<StopLossOrderConfig>,
    pub stop_limit_order_config: Option<StopLimitOrderConfig>,
}

#[derive(Debug, Serialize, Deserialize)]
/// An execution fill for an order.
pub struct Executions {
    pub effective_price: String,
    pub quantity: String,
    pub timestamp: String,
}

#[derive(Debug, Serialize, Deserialize, TypedBuilder)]
/// Parameters for a market order.
pub struct MarketOrderConfig {
    #[serde(with = "rust_decimal::serde::str")]
    pub asset_quantity: Decimal,
}

#[derive(Debug, Serialize, Deserialize, TypedBuilder)]
/// Parameters for a limit order.
pub struct LimitOrderConfig {
    // Any of these may be omitted; they also arrive as strings
    #[serde(default, with = "rust_decimal::serde::str_option")]
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quote_amount: Option<Decimal>,
    #[serde(default, with = "rust_decimal::serde::str_option")]
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub asset_quantity: Option<Decimal>,
    #[serde(default, with = "rust_decimal::serde::str_option")]
    pub limit_price: Option<Decimal>,
    // Can be absent; plain Option<String> doesn't need `default`
    pub time_in_force: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, TypedBuilder)]
/// Parameters for a stop-loss order.
pub struct StopLossOrderConfig {
    #[serde(default, with = "rust_decimal::serde::str_option")]
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quote_amount: Option<Decimal>,
    #[serde(default, with = "rust_decimal::serde::str_option")]
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub asset_quantity: Option<Decimal>,
    #[serde(default, with = "rust_decimal::serde::str_option")]
    pub stop_price: Option<Decimal>,
    pub time_in_force: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, TypedBuilder)]
/// Parameters for a stop-limit order.
pub struct StopLimitOrderConfig {
    #[serde(default, with = "rust_decimal::serde::str_option")]
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quote_amount: Option<Decimal>,
    #[serde(default, with = "rust_decimal::serde::str_option")]
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub asset_quantity: Option<Decimal>,
    #[serde(default, with = "rust_decimal::serde::str_option")]
    pub limit_price: Option<Decimal>,
    #[serde(default, with = "rust_decimal::serde::str_option")]
    pub stop_price: Option<Decimal>,
    pub time_in_force: Option<String>,
}


#[derive(Debug, Serialize, Deserialize, TypedBuilder)]
/// Query parameters for listing crypto orders.
pub struct GetCryptoOrderParams{
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at_start: Option<String>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at_end: Option<String>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub side: Option<String>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none", rename = "type")]
    pub type_: Option<String>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at_start: Option<String>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at_end: Option<String>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}
/// List crypto orders for the authenticated account using optional filters.
pub async fn get_crypto_orders(rh: &Robinhood,params: GetCryptoOrderParams) -> Result<CryptoOrdersResponse, reqwest::Error>{
    let path = String::from("/api/v1/crypto/trading/orders/");
    let headers = rh.auth_headers(&path, "GET", "");
    let client = Client::new();
    let resp = client
        .get(format!("https://trading.robinhood.com{path}"))
        .headers(headers)
        .query(&params)
        .send()
        .await?.json::<CryptoOrdersResponse>().await?;
    Ok(resp)
}

#[tokio::test]
async fn test_get_crypto_orders(){
    let rh = Robinhood::from_env();
    match get_crypto_orders(&rh, GetCryptoOrderParams::builder().build()).await{
        Ok(resp) => {
            assert_eq!(resp.previous, None);
        }
        Err(e) => {
            panic!("Error with crypto orders: {}", e);
        }
    }
}

#[derive(Debug, Serialize, Deserialize, TypedBuilder)]
/// Parameters for creating a crypto order.
pub struct CreateCyptoOrderParams{
    pub symbol: String,
    pub client_order_id: String,
    pub side: String,
    #[serde(rename = "type")]
    pub order_type: String,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub market_order_config: Option<MarketOrderConfig>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit_order_config: Option<LimitOrderConfig>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_loss_order_config: Option<StopLossOrderConfig>,
    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_limit_order_config: Option<StopLimitOrderConfig>,
}

#[derive(Debug, Serialize, Deserialize, TypedBuilder)]
/// Response returned after creating a crypto order.
pub struct CreateCryptoOrderResponse{
    pub id: String,
    pub account_number: String,
    pub symbol: String,
    pub client_order_id: String,
    pub side: String,
    pub executions: Vec<Executions>,
    #[serde(rename = "type")]
    pub order_type: String,
    pub state: String,
    #[serde(with = "rust_decimal::serde::float_option", default)]
    pub average_price: Option<Decimal>,
    #[serde(with = "rust_decimal::serde::float_option", default)]
    pub filled_asset_quantity: Option<Decimal>,
    pub created_at: String,
    pub updated_at: String,
    pub market_order_config: Option<MarketOrderConfig>,
    pub limit_order_config: Option<LimitOrderConfig>,
    pub stop_loss_order_config: Option<StopLossOrderConfig>,
    pub stop_limit_order_config: Option<StopLimitOrderConfig>,
}



#[derive(Error, Debug)]
pub enum CryptoOrderError {
    #[error("Request failed: {0}")]
    Reqwest(#[from] reqwest::Error),

    #[error("Failed to parse Robinhood response: {message}")]
    Parse {
        message: String,
        #[source]
        source: serde_json::Error,
    },
}
/// Create a new crypto order with the provided parameters.
pub async fn create_crypto_order(
    rh: &Robinhood,
    param: CreateCyptoOrderParams,
) -> Result<CreateCryptoOrderResponse, CryptoOrderError> {
    let path = "/api/v1/crypto/trading/orders/";
    let body = serde_json::to_string(&param).unwrap();
    let headers = rh.auth_headers(&path, "POST", &body);

    let client = Client::new();
    let resp = client
        .post(format!("https://trading.robinhood.com{path}"))
        .header("Content-Type", "application/json")
        .headers(headers)
        .body(body)
        .send()
        .await?;

    let text = resp.text().await?;

    match serde_json::from_str::<CreateCryptoOrderResponse>(&text) {
        Ok(parsed) => Ok(parsed),
        Err(e) => Err(CryptoOrderError::Parse {
            message: text,
            source: e,
        }),
    }
}



/// Attempt to cancel a crypto order by its ID.
pub async fn cancel_crypto_order(rh: &Robinhood, id: String) -> Result<String, reqwest::Error>{
    let path = format!("/api/v1/crypto/trading/orders/{}/cancel/", id);
    let headers = rh.auth_headers(&path, "POST", "");
    let client = Client::new();
    let resp = client
        .post(format!("https://trading.robinhood.com{path}"))
        .headers(headers)
        .send()
        .await?;
    let body = resp.text().await?;
    let cleaned = body.trim_matches('"').to_string();
    Ok(cleaned)
}

#[tokio::test]
async fn test_create_cancel_crypto_order(){
    let rh = Robinhood::from_env();
    let resp = create_crypto_order(&rh, CreateCyptoOrderParams::builder()
        .symbol("XRP-USD".to_string())
        .client_order_id(Uuid::new_v4().to_string())
        .order_type("limit".to_string())
        .side("buy".to_string())
        .limit_order_config(LimitOrderConfig::builder()
            .asset_quantity(Decimal::from(1))
            .limit_price(Option::from(Decimal::from(1)))
            .time_in_force(Option::from("gfd".to_string())).build())
        .build()).await;

    let id = match resp{
        Ok(resp) => {
            assert_eq!(resp.side, "buy");
            assert_eq!(resp.symbol, "XRP-USD");
            resp.id
        }
        Err(e) => {
            panic!("Error with crypto orders: {}", e);
        }
    };

    tokio::time::sleep(std::time::Duration::from_secs(10)).await;
    let cancel_resp = format!("Cancel request has been submitted for order {id}");
    match cancel_crypto_order(&rh, id).await{
        Ok(resp) => {
            assert_eq!(resp, cancel_resp);
        }
        Err(e) => {
            panic!("Error with crypto orders: {}", e);
        }
    }
}