rpaca 0.8.1

A rust crate wrapping the Alpaca API
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! Orders module for Alpaca API v2.
//!
//! This module provides functionality for creating, retrieving, modifying, and canceling
//! orders through Alpaca's trading API. It supports various order types including market,
//! limit, stop, and bracket orders with different time-in-force options.
//!
//! The module includes functionality for:
//! - Creating new orders with various parameters
//! - Retrieving existing orders with filtering options
//! - Replacing/modifying existing orders
//! - Canceling individual or all open orders
//! - Working with complex order types like bracket orders

use crate::auth::{Alpaca, TradingType};
use crate::request::create_trading_request;
use chrono::{DateTime, Utc};
use reqwest::Method;
use serde::{Deserialize, Serialize, Serializer};
use typed_builder::TypedBuilder;
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct Order {
    pub id: String,
    pub client_order_id: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub submitted_at: DateTime<Utc>,
    pub filled_at: Option<DateTime<Utc>>,
    pub expired_at: Option<DateTime<Utc>>,
    pub canceled_at: Option<DateTime<Utc>>,
    pub failed_at: Option<DateTime<Utc>>,
    pub replaced_at: Option<DateTime<Utc>>,
    pub replaced_by: Option<String>,
    pub replaces: Option<String>,
    pub asset_id: String,
    pub symbol: String,
    pub asset_class: String,
    pub notional: Option<String>,
    pub qty: String,
    pub filled_qty: String,
    pub filled_avg_price: Option<String>,
    pub order_class: Option<String>, // empty string => better as Option
    #[serde(rename = "order_type")]
    pub order_type: String,
    #[serde(rename = "type")]
    pub type_field: String, // 'type' is a reserved keyword
    pub side: String,
    pub position_intent: Option<String>,
    pub time_in_force: String,
    pub limit_price: Option<String>,
    pub stop_price: Option<String>,
    pub status: String,
    pub extended_hours: bool,
    pub legs: Option<serde_json::Value>, // or Option<Vec<Order>> if recursive
    pub trail_percent: Option<String>,
    pub trail_price: Option<String>,
    pub hwm: Option<String>,
    pub subtag: Option<String>,
    pub source: Option<String>,
    pub expires_at: DateTime<Utc>,
}

#[derive(Serialize, Deserialize, Debug, TypedBuilder)]
pub struct OrderRequest {
    #[builder(setter(into))]
    pub symbol: String,

    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub qty: Option<String>,

    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notional: Option<String>,

    #[builder(setter(into))]
    pub side: String,

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

    #[builder(setter(into))]
    pub time_in_force: String,

    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit_price: Option<String>,

    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_price: Option<String>,

    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trail_price: Option<String>,

    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trail_percent: Option<String>,

    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extended_hours: Option<bool>,

    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_order_id: Option<String>,

    #[builder(default, setter(strip_option, into))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_class: Option<String>,

    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub legs: Option<Vec<Legs>>,

    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub take_profit: Option<TakeProfit>,

    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_loss: Option<StopLoss>,
}

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct Legs {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub side: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub position_intent: Option<String>,

    pub symbol: String,
    pub ratio_qty: String,
}

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct TakeProfit {
    pub limit_price: String,
}

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct StopLoss {
    pub stop_price: String,
    pub limit_price: String,
}
/// Creates a new order with the specified parameters.
///
/// This function submits a new order to Alpaca's trading API with the parameters
/// specified in the OrderRequest. It supports various order types including market,
/// limit, stop, and bracket orders with different time-in-force options.
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication information
/// * `order` - The order parameters including symbol, quantity, side, type, etc.
///
/// # Returns
/// * `Result<Order, Box<dyn std::error::Error>>` - The created order information or an error
pub async fn create_order(
    alpaca: &Alpaca,
    order: OrderRequest,
) -> Result<Order, Box<dyn std::error::Error>> {
    let response = create_trading_request(alpaca, Method::POST, "/v2/orders", Some(order)).await?;
    if !response.status().is_success() {
        let status = response.status();
        {
            let text = response.text().await.unwrap_or_default();
            let message = format!("Request failed with status {}: {}", status, text);
            return Err(message.into());
        }
    }
    let info: Order = response.json().await?;
    Ok(info)
}

#[derive(Serialize, Deserialize, Debug, Default, TypedBuilder)]
pub struct GetOrdersParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub limit: Option<i128>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub after: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub until: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub direction: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub nested: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub symbols: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub side: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub asset_class: Option<String>,
}

/// Retrieves a list of orders based on the provided parameters.
///
/// This function fetches orders from Alpaca's trading API with various filtering options
/// such as status, limit, date range, direction, and symbols. It can retrieve both open
/// and closed orders.
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication information
/// * `params` - Parameters to filter the orders (status, limit, date range, etc.)
///
/// # Returns
/// * `Result<Vec<Order>, Box<dyn std::error::Error>>` - A list of orders matching the filters or an error
pub async fn get_orders(
    alpaca: &Alpaca,
    params: GetOrdersParams,
) -> Result<Vec<Order>, Box<dyn std::error::Error>> {
    // Serialize params into query string, like ?status=open&limit=50
    let query_string = serde_urlencoded::to_string(&params)?;
    let endpoint = format!("/v2/orders?{query_string}");

    let response = create_trading_request::<()>(alpaca, Method::GET, &endpoint, None).await?;

    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        let message = format!("Request failed: {text}");
        return Err(message.into());
    }

    let orders: Vec<Order> = response.json().await?;
    Ok(orders)
}
#[derive(Serialize, Deserialize, Debug)]
pub struct OrderCancel {
    pub id: Uuid,
    pub status: i128,
}
/// Cancels all open orders for the account.
///
/// This function attempts to cancel all open orders for the account. It returns
/// information about the cancellation status of each order.
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication information
///
/// # Returns
/// * `Result<Vec<Option<OrderCancel>>, Box<dyn std::error::Error>>` - A list of cancellation results or an error
pub async fn delete_all_orders(
    alpaca: &Alpaca,
) -> Result<Vec<Option<OrderCancel>>, Box<dyn std::error::Error>> {
    let response = create_trading_request::<()>(alpaca, Method::DELETE, "/v2/orders", None).await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        let message = format!("Request failed: {text}");
        return Err(message.into());
    }
    Ok(response.json().await?)
}

/// Retrieves an order by its client-assigned order ID.
///
/// This function fetches a specific order using the client-assigned order ID,
/// which is useful for tracking orders that were created by your application.
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication information
/// * `client_order_id` - The client-assigned order ID to look up
///
/// # Returns
/// * `Result<Order, Box<dyn std::error::Error>>` - The order information or an error
pub async fn get_order_by_client_order_id(
    alpaca: &Alpaca,
    client_order_id: &str,
) -> Result<Order, Box<dyn std::error::Error>> {
    let response = create_trading_request::<()>(
        alpaca,
        Method::GET,
        &format!("/v2/orders:by_client_order_id?client_order_id={client_order_id}"),
        None,
    )
    .await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        let message = format!("Request failed: {text}");
        return Err(message.into());
    }
    Ok(response.json().await?)
}

pub async fn get_order_by_id(
    alpaca: &Alpaca,
    order_id: Uuid,
    nested: Option<bool>,
) -> Result<Order, Box<dyn std::error::Error>> {
    if nested.is_none() {
        let response = create_trading_request::<()>(
            alpaca,
            Method::GET,
            &format!("/v2/orders/{order_id}"),
            None,
        )
        .await?;
        if !response.status().is_success() {
            let text = response.text().await.unwrap_or_default();
            let message = format!("Request failed: {text}");
            return Err(message.into());
        }
        Ok(response.json().await?)
    } else {
        let nested = nested.unwrap_or(false);
        let response = create_trading_request::<()>(
            alpaca,
            Method::GET,
            &format!("/v2/orders/{order_id}?nested={nested}"),
            None,
        )
        .await?;
        if !response.status().is_success() {
            let text = response.text().await.unwrap_or_default();
            let message = format!("Request failed: {text}");
            return Err(message.into());
        }
        Ok(response.json().await?)
    }
}
#[derive(Serialize, Deserialize, Debug, Default, TypedBuilder)]
pub struct ReplaceOrderParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub qty: Option<String>,
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_in_force: Option<String>,
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit_price: Option<String>,
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_price: Option<String>,
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trail: Option<String>,
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_order_id: Option<String>,
}
pub async fn replace_order_by_id(
    alpaca: &Alpaca,
    order_id: String,
    update: ReplaceOrderParams,
) -> Result<Order, Box<dyn std::error::Error>> {
    let endpoint = format!("/v2/orders/{}", order_id);
    let response = create_trading_request(alpaca, Method::PATCH, &endpoint, Some(update)).await?;

    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        return Err(format!("Replace failed: {}", text).into());
    }

    let order: Order = response.json().await?;
    Ok(order)
}

pub async fn delete_order_by_id(
    alpaca: &Alpaca,
    order_id: String,
) -> Result<(), Box<dyn std::error::Error>> {
    let endpoint = format!("/v2/orders/{}", order_id);
    let response = create_trading_request::<()>(alpaca, Method::DELETE, &endpoint, None).await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        return Err(format!("Delete failed: {}", text).into());
    }
    Ok(())
}

#[tokio::test]
async fn test_orders() {
    let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
    let create_order_response = match create_order(
        &alpaca,
        OrderRequest::builder()
            .symbol("AAPL")
            .qty("1")
            .side("buy")
            .order_type("market")
            .time_in_force("day")
            .build(),
    )
    .await
    {
        Ok(order) => {
            assert_eq!(order.qty, "1");
            assert_eq!(order.side, "buy");
            assert_eq!(order.order_type, "market");
            assert_eq!(order.time_in_force, "day");
            assert_eq!(order.symbol, "AAPL");
            order
        }
        Err(e) => panic!("Error creating order: {}", e),
    };
    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
    let get_order_response = match get_orders(
        &alpaca,
        GetOrdersParams::builder().status("all".to_string()).build(),
    )
    .await
    {
        Ok(orders) => {
            let order = match orders.clone().into_iter().find(|p| p.symbol == "AAPL") {
                Some(order) => order,
                None => {
                    println!("{orders:?}");
                    panic!("Order not found")
                }
            };
            assert_eq!(order.qty, "1");
            assert_eq!(order.side, "buy");
            assert_eq!(order.order_type, "market");
            assert_eq!(order.time_in_force, "day");
            assert_eq!(order.symbol, "AAPL");
            assert_eq!(order.client_order_id, create_order_response.client_order_id);
            order
        }
        Err(e) => panic!("Error getting orders: {}", e),
    };
    assert_eq!(create_order_response.id, get_order_response.id);
    let get_order_by_client_id = match get_order_by_client_order_id(
        &alpaca,
        &*create_order_response.client_order_id,
    )
    .await
    {
        Ok(order) => {
            assert_eq!(order.qty, "1");
            assert_eq!(order.side, "buy");
            assert_eq!(order.order_type, "market");
            assert_eq!(order.time_in_force, "day");
            assert_eq!(order.symbol, "AAPL");
            assert_eq!(order.client_order_id, create_order_response.client_order_id);
            order
        }
        Err(e) => panic!("Error getting orders by client id: {}", e),
    };
    assert_eq!(create_order_response.id, get_order_by_client_id.id);

    let get_order_by_id =
        match get_order_by_id(&alpaca, create_order_response.id.parse().unwrap(), None).await {
            Ok(order) => {
                assert_eq!(order.qty, "1");
                assert_eq!(order.side, "buy");
                assert_eq!(order.order_type, "market");
                assert_eq!(order.time_in_force, "day");
                assert_eq!(order.symbol, "AAPL");
                assert_eq!(order.client_order_id, create_order_response.client_order_id);
                order
            }
            Err(e) => panic!("Error getting orders by client id: {}", e),
        };

    assert_eq!(get_order_by_id.id, create_order_response.id);

    tokio::time::sleep(std::time::Duration::from_secs(5)).await;
    let create_order_response = match create_order(
        &alpaca,
        OrderRequest::builder()
            .symbol("AAPL")
            .qty("1")
            .time_in_force("day")
            .side("sell")
            .order_type("market")
            .build(),
    )
    .await
    {
        Ok(order) => {
            assert_eq!(order.qty, "1");
            assert_eq!(order.side, "sell");
            assert_eq!(order.order_type, "market");
            assert_eq!(order.time_in_force, "day");
            assert_eq!(order.symbol, "AAPL");
            order
        }
        Err(e) => panic!("Error creating sell order: {}", e),
    };
}