rustrade-execution 0.1.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
use crate::order::{OrderKind, TimeInForce, id::ClientOrderId};
use fnv::FnvHashMap;
use ibapi::orders::{Action, Order, TimeInForce as IbTimeInForce, order_builder};
use parking_lot::{Mutex, RwLock};
use rust_decimal::Decimal;
use rustrade_instrument::{Side, instrument::name::InstrumentNameExchange};
use std::{sync::Arc, time::Instant};

/// Order context stored when placing orders.
///
/// IB's `OrderStatus` callback doesn't include instrument/side/price/kind,
/// so we store this context at order placement time to reconstruct full
/// `Order` structs from status updates.
///
/// # Invariant
///
/// This data is immutable after order placement. IB doesn't support in-flight
/// order modification — amendments are cancel+replace (new order ID, new entry).
#[derive(Debug, Clone)]
pub struct OrderContext {
    pub instrument: InstrumentNameExchange,
    pub side: Side,
    pub price: Decimal,
    pub quantity: Decimal,
    pub kind: OrderKind,
    pub time_in_force: TimeInForce,
}

/// Bidirectional mapping between rustrade ClientOrderId and IB order IDs.
///
/// IB uses `i32` order IDs from a sequence. Barter uses `ClientOrderId` (SmolStr).
/// This map maintains the bidirectional relationship and stores order context
/// for reconstructing full `Order` structs from `OrderStatus` callbacks.
#[derive(Debug, Clone)]
pub struct OrderIdMap {
    inner: Arc<RwLock<OrderIdMapInner>>,
}

#[derive(Debug, Default)]
struct OrderIdMapInner {
    cid_to_ib: FnvHashMap<ClientOrderId, i32>,
    /// Merged map: IB order ID → (ClientOrderId, OrderContext, registration time) for single-lookup on hot path.
    /// The Instant tracks when the order was registered, enabling age-based cleanup.
    ib_to_entry: FnvHashMap<i32, (ClientOrderId, OrderContext, Instant)>,
}

impl OrderIdMap {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(OrderIdMapInner::default())),
        }
    }

    /// Register a mapping between ClientOrderId and IB order ID with order context.
    pub fn register(&self, client_id: ClientOrderId, ib_id: i32, context: OrderContext) {
        let mut inner = self.inner.write();
        inner.cid_to_ib.insert(client_id.clone(), ib_id);
        inner
            .ib_to_entry
            .insert(ib_id, (client_id, context, Instant::now()));
    }

    /// Look up IB order ID by ClientOrderId.
    pub fn get_ib_id(&self, client_id: &ClientOrderId) -> Option<i32> {
        self.inner.read().cid_to_ib.get(client_id).copied()
    }

    /// Look up ClientOrderId by IB order ID.
    pub fn get_client_id(&self, ib_id: i32) -> Option<ClientOrderId> {
        self.inner
            .read()
            .ib_to_entry
            .get(&ib_id)
            .map(|(cid, _, _)| cid.clone())
    }

    /// Look up ClientOrderId and OrderContext together by IB order ID (single lookup).
    pub fn get_client_id_and_context(&self, ib_id: i32) -> Option<(ClientOrderId, OrderContext)> {
        self.inner
            .read()
            .ib_to_entry
            .get(&ib_id)
            .map(|(cid, ctx, _)| (cid.clone(), ctx.clone()))
    }

    /// Remove mapping and return context in a single write lock acquisition.
    ///
    /// Use this for terminal status events (Cancelled/Inactive) to avoid the
    /// read-then-write pattern of `get_client_id_and_context` + `remove_by_ib_id`.
    pub fn remove_and_get_context(&self, ib_id: i32) -> Option<(ClientOrderId, OrderContext)> {
        let mut inner = self.inner.write();
        if let Some((client_id, ctx, _)) = inner.ib_to_entry.remove(&ib_id) {
            inner.cid_to_ib.remove(&client_id);
            Some((client_id, ctx))
        } else {
            None
        }
    }

    /// Remove a mapping by IB order ID (used when order is fully filled/cancelled).
    pub fn remove_by_ib_id(&self, ib_id: i32) -> Option<ClientOrderId> {
        let mut inner = self.inner.write();
        if let Some((client_id, _, _)) = inner.ib_to_entry.remove(&ib_id) {
            inner.cid_to_ib.remove(&client_id);
            Some(client_id)
        } else {
            None
        }
    }

    /// Clear order ID mappings older than the given duration.
    ///
    /// Returns the number of cleared entries.
    ///
    /// # Why This Is Needed
    ///
    /// IB does not guarantee event ordering between `OrderStatus("Filled")` and
    /// `ExecutionData`/`CommissionReport`. For fast-filling orders (especially
    /// market orders), execution data may arrive AFTER the filled status — or
    /// the filled status may not arrive at all. Removing mappings on terminal
    /// status would cause data loss.
    ///
    /// Instead, call this method periodically to clean up old mappings. A
    /// reasonable interval is 5-10 minutes with a max_age of 1 hour.
    pub fn clear_stale(&self, max_age: std::time::Duration) -> usize {
        let mut inner = self.inner.write();
        let before = inner.ib_to_entry.len();

        // Collect IB IDs to remove (can't mutate while iterating)
        let stale_ids: Vec<i32> = inner
            .ib_to_entry
            .iter()
            .filter(|(_, (_, _, registered_at))| registered_at.elapsed() >= max_age)
            .map(|(ib_id, _)| *ib_id)
            .collect();

        for ib_id in stale_ids {
            if let Some((client_id, _, _)) = inner.ib_to_entry.remove(&ib_id) {
                inner.cid_to_ib.remove(&client_id);
            }
        }

        before - inner.ib_to_entry.len()
    }

    /// Number of active mappings.
    pub fn len(&self) -> usize {
        self.inner.read().cid_to_ib.len()
    }

    /// Check if map is empty.
    pub fn is_empty(&self) -> bool {
        self.inner.read().cid_to_ib.is_empty()
    }
}

impl Default for OrderIdMap {
    fn default() -> Self {
        Self::new()
    }
}

/// Tracks IB order IDs with pending cancel requests.
///
/// Used to differentiate user-initiated cancellation from time-based expiration.
/// IBKR sends `"Cancelled"` status for both cases; this map tracks which cancels
/// were user-initiated via `cancel_order()`.
#[derive(Debug, Clone)]
pub struct PendingCancels {
    inner: Arc<Mutex<FnvHashMap<i32, Instant>>>,
}

impl PendingCancels {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(FnvHashMap::with_capacity_and_hasher(
                8,
                Default::default(),
            ))),
        }
    }

    /// Record a pending cancel request for the given IB order ID.
    pub fn insert(&self, ib_id: i32) {
        self.inner.lock().insert(ib_id, Instant::now());
    }

    /// Check if a cancel was user-initiated and remove from tracking.
    ///
    /// Returns `true` if the order ID was in the pending set (user-initiated cancel).
    #[must_use]
    pub fn remove(&self, ib_id: i32) -> bool {
        self.inner.lock().remove(&ib_id).is_some()
    }

    /// Clear entries older than the given duration.
    ///
    /// Returns the number of cleared entries. Call periodically to prevent
    /// memory leaks from orphaned cancel requests (e.g., network issues).
    #[must_use]
    pub fn clear_stale(&self, max_age: std::time::Duration) -> usize {
        let mut map = self.inner.lock();
        let before = map.len();
        map.retain(|_, registered_at| registered_at.elapsed() < max_age);
        before - map.len()
    }

    /// Number of pending cancel requests being tracked.
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.lock().len()
    }

    /// Check if there are no pending cancel requests.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.lock().is_empty()
    }
}

impl Default for PendingCancels {
    fn default() -> Self {
        Self::new()
    }
}

/// Convert rustrade Side to IB Action.
pub fn side_to_action(side: rustrade_instrument::Side) -> Action {
    match side {
        rustrade_instrument::Side::Buy => Action::Buy,
        rustrade_instrument::Side::Sell => Action::Sell,
    }
}

/// Error when mapping rustrade order types to IB.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OrderMappingError {
    PostOnlyNotSupported,
    /// Price conversion to f64 failed (overflow or invalid decimal).
    InvalidPrice(String),
}

impl std::fmt::Display for OrderMappingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::PostOnlyNotSupported => write!(f, "post_only not supported by IB"),
            Self::InvalidPrice(p) => write!(f, "invalid price for f64 conversion: {p}"),
        }
    }
}

impl std::error::Error for OrderMappingError {}

/// Convert rustrade TimeInForce to IB TimeInForce.
pub fn time_in_force_to_ib(tif: &TimeInForce) -> Result<IbTimeInForce, OrderMappingError> {
    match tif {
        TimeInForce::GoodUntilCancelled { post_only } => {
            if *post_only {
                Err(OrderMappingError::PostOnlyNotSupported)
            } else {
                Ok(IbTimeInForce::GoodTilCanceled)
            }
        }
        TimeInForce::GoodUntilEndOfDay => Ok(IbTimeInForce::Day),
        TimeInForce::FillOrKill => Ok(IbTimeInForce::FillOrKill),
        TimeInForce::ImmediateOrCancel => Ok(IbTimeInForce::ImmediateOrCancel),
    }
}

/// Build an IB Order from rustrade order parameters.
pub fn build_ib_order(
    side: rustrade_instrument::Side,
    quantity: f64,
    kind: &OrderKind,
    price: rust_decimal::Decimal,
    tif: &TimeInForce,
) -> Result<Order, OrderMappingError> {
    let action = side_to_action(side);
    let tif_ib = time_in_force_to_ib(tif)?;

    let mut order = match kind {
        OrderKind::Market => order_builder::market_order(action, quantity),
        OrderKind::Limit => {
            let price_f64: f64 = price.try_into().or_else(|_| {
                price
                    .to_string()
                    .parse()
                    .map_err(|_| OrderMappingError::InvalidPrice(price.to_string()))
            })?;
            order_builder::limit_order(action, quantity, price_f64)
        }
    };

    order.tif = tif_ib;

    Ok(order)
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Test code: panics are the correct failure mode
mod tests {
    use super::*;
    use rust_decimal::Decimal;

    fn test_context() -> OrderContext {
        OrderContext {
            instrument: rustrade_instrument::instrument::name::InstrumentNameExchange::from("AAPL"),
            side: Side::Buy,
            price: Decimal::from(150),
            quantity: Decimal::from(100),
            kind: OrderKind::Limit,
            time_in_force: TimeInForce::GoodUntilCancelled { post_only: false },
        }
    }

    #[test]
    fn test_order_id_map_basic() {
        let map = OrderIdMap::new();
        let cid = ClientOrderId::new("order-123");
        let ctx = test_context();

        map.register(cid.clone(), 42, ctx.clone());

        assert_eq!(map.get_ib_id(&cid), Some(42));
        assert_eq!(map.get_client_id(42), Some(cid.clone()));
        assert_eq!(map.len(), 1);

        let (retrieved_cid, retrieved_ctx) = map.get_client_id_and_context(42).unwrap();
        assert_eq!(retrieved_cid, cid);
        assert_eq!(retrieved_ctx.side, Side::Buy);
        assert_eq!(retrieved_ctx.price, Decimal::from(150));
    }

    #[test]
    fn test_order_id_map_remove() {
        let map = OrderIdMap::new();
        let cid = ClientOrderId::new("order-456");

        map.register(cid.clone(), 100, test_context());
        assert_eq!(map.len(), 1);

        let removed = map.remove_by_ib_id(100);
        assert_eq!(removed, Some(cid.clone()));
        assert!(map.is_empty());
        assert!(map.get_ib_id(&cid).is_none());
        assert!(map.get_client_id(100).is_none());
        assert!(map.get_client_id_and_context(100).is_none());
    }

    #[test]
    fn test_side_conversion() {
        assert!(matches!(
            side_to_action(rustrade_instrument::Side::Buy),
            Action::Buy
        ));
        assert!(matches!(
            side_to_action(rustrade_instrument::Side::Sell),
            Action::Sell
        ));
    }

    #[test]
    fn test_time_in_force_conversion() {
        assert_eq!(
            time_in_force_to_ib(&TimeInForce::GoodUntilCancelled { post_only: false }),
            Ok(IbTimeInForce::GoodTilCanceled)
        );

        assert!(matches!(
            time_in_force_to_ib(&TimeInForce::GoodUntilCancelled { post_only: true }),
            Err(OrderMappingError::PostOnlyNotSupported)
        ));

        assert_eq!(
            time_in_force_to_ib(&TimeInForce::GoodUntilEndOfDay),
            Ok(IbTimeInForce::Day)
        );
        assert_eq!(
            time_in_force_to_ib(&TimeInForce::FillOrKill),
            Ok(IbTimeInForce::FillOrKill)
        );
        assert_eq!(
            time_in_force_to_ib(&TimeInForce::ImmediateOrCancel),
            Ok(IbTimeInForce::ImmediateOrCancel)
        );
    }

    #[test]
    fn test_build_market_order() {
        let order = build_ib_order(
            rustrade_instrument::Side::Buy,
            100.0,
            &OrderKind::Market,
            rust_decimal::Decimal::ZERO,
            &TimeInForce::GoodUntilEndOfDay,
        )
        .unwrap();

        assert_eq!(order.action, Action::Buy);
        assert_eq!(order.total_quantity, 100.0);
        assert_eq!(order.order_type, "MKT");
    }

    #[test]
    fn test_build_limit_order() {
        let order = build_ib_order(
            rustrade_instrument::Side::Sell,
            50.0,
            &OrderKind::Limit,
            Decimal::try_from(150.5).unwrap(),
            &TimeInForce::GoodUntilCancelled { post_only: false },
        )
        .unwrap();

        assert_eq!(order.action, Action::Sell);
        assert_eq!(order.total_quantity, 50.0);
        assert_eq!(order.order_type, "LMT");
    }

    #[test]
    fn test_order_id_map_remove_and_get_context() {
        let map = OrderIdMap::new();
        let cid = ClientOrderId::new("order-789");
        let ctx = test_context();

        map.register(cid.clone(), 50, ctx);
        assert_eq!(map.len(), 1);

        // Remove and get context in single operation
        let result = map.remove_and_get_context(50);
        assert!(result.is_some());
        let (retrieved_cid, retrieved_ctx) = result.unwrap();
        assert_eq!(retrieved_cid, cid);
        assert_eq!(retrieved_ctx.side, Side::Buy);

        // Map should be empty now
        assert!(map.is_empty());
        assert!(map.get_client_id(50).is_none());
        assert!(map.get_ib_id(&cid).is_none());

        // Second removal returns None
        assert!(map.remove_and_get_context(50).is_none());
    }

    #[test]
    fn test_order_id_map_clear_stale() {
        use std::time::Duration;

        let map = OrderIdMap::new();

        // Register orders
        map.register(ClientOrderId::new("old-1"), 1, test_context());
        map.register(ClientOrderId::new("old-2"), 2, test_context());

        // With zero max_age, all entries are stale
        let cleared = map.clear_stale(Duration::ZERO);
        assert_eq!(cleared, 2);
        assert!(map.is_empty());

        // Register new orders
        map.register(ClientOrderId::new("new-1"), 10, test_context());
        map.register(ClientOrderId::new("new-2"), 20, test_context());

        // With large max_age, nothing is stale
        let cleared = map.clear_stale(Duration::from_secs(3600));
        assert_eq!(cleared, 0);
        assert_eq!(map.len(), 2);
    }

    #[test]
    fn test_pending_cancels_insert_remove() {
        let cancels = PendingCancels::new();
        assert!(cancels.is_empty());

        // Insert a cancel request
        cancels.insert(42);
        assert_eq!(cancels.len(), 1);
        assert!(!cancels.is_empty());

        // Remove returns true for tracked ID
        assert!(cancels.remove(42));
        assert!(cancels.is_empty());

        // Remove returns false for untracked ID
        assert!(!cancels.remove(42));
        assert!(!cancels.remove(999));
    }

    #[test]
    fn test_pending_cancels_multiple() {
        let cancels = PendingCancels::new();

        cancels.insert(1);
        cancels.insert(2);
        cancels.insert(3);
        assert_eq!(cancels.len(), 3);

        // Remove middle one
        assert!(cancels.remove(2));
        assert_eq!(cancels.len(), 2);

        // Other IDs still tracked
        assert!(cancels.remove(1));
        assert!(cancels.remove(3));
        assert!(cancels.is_empty());
    }

    #[test]
    fn test_pending_cancels_clear_stale() {
        use std::time::Duration;

        let cancels = PendingCancels::new();

        cancels.insert(1);
        cancels.insert(2);

        // With zero max_age, all entries are stale
        let cleared = cancels.clear_stale(Duration::ZERO);
        assert_eq!(cleared, 2);
        assert!(cancels.is_empty());

        // Insert new ones
        cancels.insert(10);
        cancels.insert(20);

        // With large max_age, nothing is stale
        let cleared = cancels.clear_stale(Duration::from_secs(3600));
        assert_eq!(cleared, 0);
        assert_eq!(cancels.len(), 2);
    }

    #[test]
    fn test_pending_cancels_duplicate_insert() {
        let cancels = PendingCancels::new();

        cancels.insert(42);
        cancels.insert(42);

        // HashMap deduplicates by ID; second insert updates timestamp
        assert_eq!(cancels.len(), 1);
        assert!(cancels.remove(42));
        assert!(cancels.is_empty());
    }
}