rustrade-execution 0.15.0

Stream private account data from financial venues, and execute (live or mock) orders.
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use crate::order::{
    id::StrategyId,
    request::{OrderRequestCancel, OrderRequestOpen, RequestCancel, RequestOpen},
    state::UnindexedOrderState,
};
use chrono::{DateTime, Utc};
use derive_more::{Constructor, Display};
use id::ClientOrderId;
use rust_decimal::Decimal;
use rustrade_instrument::{
    Side,
    asset::{AssetIndex, name::AssetNameExchange},
    exchange::{ExchangeId, ExchangeIndex},
    instrument::{InstrumentIndex, name::InstrumentNameExchange},
};
use serde::{Deserialize, Serialize};
use state::{
    ActiveOrderState, Cancelled, Expired, InactiveOrderState, Open, OpenInFlight, OrderState,
};

/// `Order` related identifiers.
pub mod id;

/// `Order` states.
///
/// eg/ `OpenInFlight`, `Open`, `Rejected`, `Expired`, etc.
pub mod state;

/// Order open and cancel request types.
///
/// ie/ `OrderRequestOpen` & `OrderRequestCancel`.
pub mod request;

/// Bracket order types for the [`BracketOrderClient`](crate::client::BracketOrderClient) trait.
pub mod bracket;

/// Convenient type alias for an [`Order`] keyed with [`ExchangeId`] and [`InstrumentNameExchange`].
pub type UnindexedOrder = Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>;

/// Convenient type alias for an [`OrderKey`] keyed with [`ExchangeId`]
/// and [`InstrumentNameExchange`].
pub type UnindexedOrderKey = OrderKey<ExchangeId, InstrumentNameExchange>;

/// Convenient type alias for an [`Order`] that has ended, keyed with [`ExchangeId`] and
/// [`InstrumentNameExchange`].
pub type UnindexedInactiveOrder =
    Order<ExchangeId, InstrumentNameExchange, state::UnindexedInactiveOrderState>;

/// Convenient type alias for an [`OrderSnapshot`] keyed with [`ExchangeId`], [`AssetNameExchange`],
/// and [`InstrumentNameExchange`].
pub type UnindexedOrderSnapshot = Order<
    ExchangeId,
    InstrumentNameExchange,
    OrderState<AssetNameExchange, InstrumentNameExchange>,
>;

/// Convenient type alias for an [`Order`] [`OrderState`] snapshot.
pub type OrderSnapshot<
    ExchangeKey = ExchangeIndex,
    AssetKey = AssetIndex,
    InstrumentKey = InstrumentIndex,
> = Order<ExchangeKey, InstrumentKey, OrderState<AssetKey, InstrumentKey>>;

#[derive(
    Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Constructor,
)]

pub struct OrderEvent<State, ExchangeKey = ExchangeIndex, InstrumentKey = InstrumentIndex> {
    pub key: OrderKey<ExchangeKey, InstrumentKey>,
    pub state: State,
}

#[derive(
    Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Constructor,
)]
pub struct OrderKey<ExchangeKey = ExchangeIndex, InstrumentKey = InstrumentIndex> {
    pub exchange: ExchangeKey,
    pub instrument: InstrumentKey,
    pub strategy: StrategyId,
    pub cid: ClientOrderId,
}

impl<ExchangeKey, InstrumentKey> OrderKey<ExchangeKey, &InstrumentKey>
where
    InstrumentKey: Clone,
{
    /// Clones the borrowed instrument key, producing a key that outlives what it was read from.
    ///
    /// An index that maps an [`InstrumentIndex`] back to an exchange-native name hands out a
    /// borrow of the name it owns. Anything that stores the key, sends it to another task, or
    /// hands it to a venue needs it owned, and every such site would otherwise write out this
    /// same four-field rebuild.
    pub fn into_owned_instrument(self) -> OrderKey<ExchangeKey, InstrumentKey> {
        let Self {
            exchange,
            instrument,
            strategy,
            cid,
        } = self;

        OrderKey {
            exchange,
            instrument: instrument.clone(),
            strategy,
            cid,
        }
    }
}

impl<State, ExchangeKey, InstrumentKey> OrderEvent<State, ExchangeKey, &InstrumentKey>
where
    InstrumentKey: Clone,
{
    /// Clones the borrowed instrument key, producing an event that outlives what it was read from.
    ///
    /// See [`OrderKey::into_owned_instrument`]; the state travels untouched.
    pub fn into_owned_instrument(self) -> OrderEvent<State, ExchangeKey, InstrumentKey> {
        let Self { key, state } = self;

        OrderEvent {
            key: key.into_owned_instrument(),
            state,
        }
    }
}

#[derive(
    Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Constructor,
)]
pub struct Order<ExchangeKey = ExchangeIndex, InstrumentKey = InstrumentIndex, State = OrderState> {
    pub key: OrderKey<ExchangeKey, InstrumentKey>,
    pub side: Side,
    /// Limit price for the order. `None` for Market/Stop/TrailingStop orders, and for a
    /// TrailingStopLimit, whose limit follows its stop; the fixed limit of a
    /// TrailingStopFixedLimit.
    pub price: Option<Decimal>,
    pub quantity: Decimal,
    pub kind: OrderKind,
    pub time_in_force: TimeInForce,
    pub state: State,
}

impl<ExchangeKey, InstrumentKey, State> Order<ExchangeKey, InstrumentKey, State> {
    /// This order with its state replaced by `f` of it, every other field unchanged.
    pub fn map_state<NewState>(
        self,
        f: impl FnOnce(State) -> NewState,
    ) -> Order<ExchangeKey, InstrumentKey, NewState> {
        let Order {
            key,
            side,
            price,
            quantity,
            kind,
            time_in_force,
            state,
        } = self;

        Order {
            key,
            side,
            price,
            quantity,
            kind,
            time_in_force,
            state: f(state),
        }
    }
}

impl<ExchangeKey, AssetKey, InstrumentKey>
    Order<ExchangeKey, InstrumentKey, OrderState<AssetKey, InstrumentKey>>
{
    pub fn to_active(&self) -> Option<Order<ExchangeKey, InstrumentKey, ActiveOrderState>>
    where
        ExchangeKey: Clone,
        InstrumentKey: Clone,
    {
        let OrderState::Active(state) = &self.state else {
            return None;
        };

        Some(Order {
            key: self.key.clone(),
            side: self.side,
            price: self.price,
            quantity: self.quantity,
            kind: self.kind,
            time_in_force: self.time_in_force,
            state: state.clone(),
        })
    }

    pub fn to_inactive(
        &self,
    ) -> Option<Order<ExchangeKey, InstrumentKey, InactiveOrderState<AssetKey, InstrumentKey>>>
    where
        ExchangeKey: Clone,
        AssetKey: Clone,
        InstrumentKey: Clone,
    {
        let OrderState::Inactive(state) = &self.state else {
            return None;
        };

        Some(Order {
            key: self.key.clone(),
            side: self.side,
            price: self.price,
            quantity: self.quantity,
            kind: self.kind,
            time_in_force: self.time_in_force,
            state: state.clone(),
        })
    }
}

impl<ExchangeKey, InstrumentKey> Order<ExchangeKey, InstrumentKey, ActiveOrderState>
where
    ExchangeKey: Clone,
    InstrumentKey: Clone,
{
    pub fn to_request_cancel(&self) -> Option<OrderRequestCancel<ExchangeKey, InstrumentKey>> {
        let Order { key, state, .. } = self;

        let request_cancel = match state {
            ActiveOrderState::OpenInFlight(_) => RequestCancel { id: None },
            ActiveOrderState::Open(open) => RequestCancel {
                id: Some(open.id.clone()),
            },
            _ => return None,
        };

        Some(OrderRequestCancel {
            key: key.clone(),
            state: request_cancel,
        })
    }
}

/// Specifies how the trailing offset is measured for trailing stop orders.
///
/// Different exchanges support different offset types:
/// - IBKR: Absolute (dollar amount) and Percentage
/// - Binance: BasisPoints (1/100th of 1%)
/// - Alpaca/Coinbase: Do not support trailing stops
#[derive(
    Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Display,
)]
pub enum TrailingOffsetType {
    /// Absolute dollar/currency amount (e.g., $2.00 trailing distance).
    Absolute,
    /// Percentage of the current price (e.g., 5% trailing distance).
    Percentage,
    /// Basis points (1/100th of 1%). What Binance's `trailingDelta` takes.
    BasisPoints,
}

#[derive(
    Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Display,
)]
#[non_exhaustive]
pub enum OrderKind {
    Market,
    Limit,
    /// Stop (market) order - triggers a market order when trigger_price is reached.
    #[display("Stop({trigger_price})")]
    Stop {
        trigger_price: Decimal,
    },
    /// Stop-limit order - triggers a limit order at Order.price when trigger_price is reached.
    #[display("StopLimit({trigger_price})")]
    StopLimit {
        trigger_price: Decimal,
    },
    /// Take-profit (market) order - triggers a market order when trigger_price is reached.
    /// Opposite of Stop: triggers when price moves favorably (above for longs, below for shorts).
    #[display("TakeProfit({trigger_price})")]
    TakeProfit {
        trigger_price: Decimal,
    },
    /// Take-profit limit order - triggers a limit order at Order.price when trigger_price is reached.
    #[display("TakeProfitLimit({trigger_price})")]
    TakeProfitLimit {
        trigger_price: Decimal,
    },
    /// Trailing stop order - stop price trails the market by a specified offset.
    #[display("TrailingStop({offset}, {offset_type}, activation: {activation_price:?})")]
    TrailingStop {
        offset: Decimal,
        offset_type: TrailingOffsetType,
        /// The price the market must reach before the stop starts trailing, or `None` to trail
        /// from the next trade.
        ///
        /// Which way the market must reach it is the venue's. On Binance spot and margin, whose
        /// trailing stop is a `STOP_LOSS` with a `stopPrice`, a sell starts trailing once the
        /// market is at or below it and a buy once at or above it. A client whose venue has no
        /// activation price rejects `Some` with
        /// [`OrderError::UnsupportedOrderType`](crate::error::OrderError::UnsupportedOrderType),
        /// and one that sends it refuses a price that is not positive.
        ///
        /// Read back from a venue, it is the price the venue reports in the same field, which
        /// Binance does not document as fixed once the stop activates.
        activation_price: Option<Decimal>,
    },
    /// Trailing stop-limit order - when triggered, submits a limit order offset from the stop.
    ///
    /// The limit price follows from the stop and `limit_offset`, so the order takes no `price`.
    #[display("TrailingStopLimit({offset}, {offset_type}, {stop_price}, {limit_offset})")]
    TrailingStopLimit {
        offset: Decimal,
        offset_type: TrailingOffsetType,
        /// The stop price at submission; it then trails the market by `offset`. Must be positive.
        ///
        /// The venue may trail it straight away. On IBKR paper, a stop within `offset` of the
        /// market was kept as placed, and one further away moved to `offset` from the market
        /// within seconds of IB accepting the order, for buys and sells, absolute and percentage
        /// trails. So an order read back from a venue listing may report the stop after it has
        /// trailed, not the one it was placed with.
        stop_price: Decimal,
        /// Offset from the triggered stop price to set the limit price.
        limit_offset: Decimal,
    },
    /// Trailing stop whose limit price is fixed when it is placed: only the trigger trails, and
    /// once it triggers the order works at [`OrderRequestOpen`]'s `price`, as a
    /// [`StopLimit`](Self::StopLimit) does. Binance spot and margin's `STOP_LOSS_LIMIT` with a
    /// `trailingDelta`.
    ///
    /// Unlike [`TrailingStopLimit`](Self::TrailingStopLimit), whose limit follows the triggered
    /// stop. A client whose venue has no such order rejects it with
    /// [`OrderError::UnsupportedOrderType`](crate::error::OrderError::UnsupportedOrderType).
    #[display("TrailingStopFixedLimit({offset}, {offset_type}, activation: {activation_price:?})")]
    TrailingStopFixedLimit {
        offset: Decimal,
        offset_type: TrailingOffsetType,
        /// As [`TrailingStop`](Self::TrailingStop)'s `activation_price`.
        activation_price: Option<Decimal>,
    },
}

#[derive(
    Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Display,
)]
pub enum TimeInForce {
    GoodUntilCancelled {
        post_only: bool,
    },
    GoodUntilEndOfDay,
    FillOrKill,
    ImmediateOrCancel,
    /// Good until a specific date/time. Order expires if not filled by the specified time.
    #[display("GoodTillDate({expiry})")]
    GoodTillDate {
        expiry: DateTime<Utc>,
    },
    /// Execute at market open (OPG). Valid for various order types.
    AtOpen,
    /// Execute at market close. Only valid with Market (→ MOC) or Limit (→ LOC) orders.
    AtClose,
}

impl<ExchangeKey, InstrumentKey> Order<ExchangeKey, InstrumentKey, ActiveOrderState>
where
    ExchangeKey: Clone,
    InstrumentKey: Clone,
{
    /// The order an open request describes, [`OpenInFlight`] since `time_sent`.
    pub fn open_in_flight(
        request: &OrderRequestOpen<ExchangeKey, InstrumentKey>,
        time_sent: DateTime<Utc>,
    ) -> Self {
        let OrderRequestOpen {
            key,
            state:
                RequestOpen {
                    side,
                    price,
                    quantity,
                    kind,
                    time_in_force,
                    position_id: _,
                    reduce_only: _, // used by adapters (e.g., Alpaca) to derive position_intent
                    market: _,      // decision-time provenance; not part of the resulting Order
                    margin_effect: _, // an instruction to the venue; not part of the resulting Order
                },
        } = request;

        Self {
            key: key.clone(),
            side: *side,
            price: *price,
            quantity: *quantity,
            kind: *kind,
            time_in_force: *time_in_force,
            state: ActiveOrderState::OpenInFlight(OpenInFlight::new(time_sent)),
        }
    }
}

impl<ExchangeKey, InstrumentKey> From<Order<ExchangeKey, InstrumentKey, Open>>
    for Order<ExchangeKey, InstrumentKey, ActiveOrderState>
{
    fn from(value: Order<ExchangeKey, InstrumentKey, Open>) -> Self {
        value.map_state(ActiveOrderState::Open)
    }
}

impl<ExchangeKey, AssetKey, InstrumentKey> From<Order<ExchangeKey, InstrumentKey, Open>>
    for Order<ExchangeKey, InstrumentKey, OrderState<AssetKey, InstrumentKey>>
{
    fn from(value: Order<ExchangeKey, InstrumentKey, Open>) -> Self {
        value.map_state(|state| OrderState::Active(ActiveOrderState::Open(state)))
    }
}

impl<ExchangeKey, AssetKey, InstrumentKey> From<Order<ExchangeKey, InstrumentKey, Cancelled>>
    for Order<ExchangeKey, InstrumentKey, OrderState<AssetKey, InstrumentKey>>
{
    fn from(value: Order<ExchangeKey, InstrumentKey, Cancelled>) -> Self {
        value.map_state(|state| OrderState::Inactive(InactiveOrderState::Cancelled(state)))
    }
}

impl<ExchangeKey, AssetKey, InstrumentKey> From<Order<ExchangeKey, InstrumentKey, Expired>>
    for Order<ExchangeKey, InstrumentKey, OrderState<AssetKey, InstrumentKey>>
{
    fn from(value: Order<ExchangeKey, InstrumentKey, Expired>) -> Self {
        value.map_state(|state| OrderState::Inactive(InactiveOrderState::Expired(state)))
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Test code: panics on bad input are acceptable
mod tests {
    use super::*;
    use rust_decimal_macros::dec;

    #[test]
    fn order_kind_display_take_profit() {
        let tp = OrderKind::TakeProfit {
            trigger_price: dec!(100.50),
        };
        assert_eq!(tp.to_string(), "TakeProfit(100.50)");
    }

    #[test]
    fn order_kind_display_take_profit_limit() {
        let tpl = OrderKind::TakeProfitLimit {
            trigger_price: dec!(200.25),
        };
        assert_eq!(tpl.to_string(), "TakeProfitLimit(200.25)");
    }

    #[test]
    fn order_kind_serde_roundtrip_take_profit() {
        let original = OrderKind::TakeProfit {
            trigger_price: dec!(150.00),
        };
        let json = serde_json::to_string(&original).unwrap();
        let deserialized: OrderKind = serde_json::from_str(&json).unwrap();
        assert_eq!(original, deserialized);
    }

    #[test]
    fn order_kind_serde_roundtrip_take_profit_limit() {
        let original = OrderKind::TakeProfitLimit {
            trigger_price: dec!(250.75),
        };
        let json = serde_json::to_string(&original).unwrap();
        let deserialized: OrderKind = serde_json::from_str(&json).unwrap();
        assert_eq!(original, deserialized);
    }
    /// The trailing kinds round-trip with and without an activation price, and a `TrailingStop`
    /// stored before it had one still loads, without one. Display shows it.
    #[test]
    fn trailing_kinds_round_trip_and_a_stored_trailing_stop_loads() {
        for activation_price in [None, Some(dec!(105))] {
            for original in [
                OrderKind::TrailingStop {
                    offset: dec!(1),
                    offset_type: TrailingOffsetType::Percentage,
                    activation_price,
                },
                OrderKind::TrailingStopFixedLimit {
                    offset: dec!(25),
                    offset_type: TrailingOffsetType::BasisPoints,
                    activation_price,
                },
            ] {
                let json = serde_json::to_string(&original).unwrap();
                let deserialized: OrderKind = serde_json::from_str(&json).unwrap();
                assert_eq!(original, deserialized);
            }
        }
        let stored: OrderKind =
            serde_json::from_str(r#"{"TrailingStop":{"offset":"1","offset_type":"Percentage"}}"#)
                .unwrap();
        assert_eq!(
            stored,
            OrderKind::TrailingStop {
                offset: dec!(1),
                offset_type: TrailingOffsetType::Percentage,
                activation_price: None,
            }
        );
        assert_eq!(
            OrderKind::TrailingStop {
                offset: dec!(1),
                offset_type: TrailingOffsetType::Percentage,
                activation_price: Some(dec!(105)),
            }
            .to_string(),
            "TrailingStop(1, Percentage, activation: Some(105))"
        );
    }
}