ibcore 0.2.1

Standalone IB Gateway integration layer wrapping ibapi — diagnostic events, structured errors, market data snapshots
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! Order placement, cancellation, and status tracking.
//!
//! Provides methods on [`IbClient`](crate::IbClient) for submitting orders,
//! cancelling them, and subscribing to order status updates.
//!
//! # Design
//! All methods are async and return [`IbError`](crate::IbError) on failure.
//! Order IDs are auto-assigned via [`ibapi::Client::next_valid_order_id`]
//! — callers never manage raw IDs.

use crate::diagnostics::DiagnosticEvent;
use crate::errors::IbError;
use crate::IbClient;
use futures::StreamExt;
use futures::stream::BoxStream;
use ibapi::contracts::Contract;
use ibapi::orders::Order;
use ibapi::subscriptions::SubscriptionItemStreamExt;

// Re-export key types for the pub API
pub use ibapi::orders::{Action, OrderStatusKind, TimeInForce};

/// Snapshot of an open order with its contract.
///
/// Returned by [`IbClient::open_orders`] as a one-shot summary.
#[derive(Debug, Clone, PartialEq)]
pub struct OpenOrder {
    /// The API-assigned order ID.
    pub order_id: i32,
    /// Ticker symbol of the underlying contract.
    pub symbol: String,
    /// Order side: "BUY" or "SELL".
    pub action: String,
    /// Total order quantity.
    pub quantity: f64,
    /// Order type string (e.g. "LMT", "MKT", "STP").
    pub order_type: String,
    /// Limit price, if applicable.
    pub limit_price: Option<f64>,
    /// Current order status string.
    pub status: String,
    /// Number of contracts/shares already filled.
    pub filled_qty: f64,
    /// Number of contracts/shares still open.
    pub remaining_qty: f64,
}

/// Typed order status event (not raw ibapi enum).
///
/// Provides a simplified, typed view of order state changes from IB's
/// order update stream. Consumers match on these variants instead of
/// interpreting raw [`ibapi::orders::OrderStatus`] fields.
#[derive(Debug, Clone, PartialEq)]
pub enum OrderStatusEvent {
    /// Order was acknowledged by IB.
    Submitted {
        /// The API-assigned order ID.
        order_id: i32,
    },
    /// Order was filled (partially or fully).
    Filled {
        /// The API-assigned order ID.
        order_id: i32,
        /// Number of contracts/shares filled.
        filled_qty: f64,
        /// Average fill price.
        avg_price: f64,
        /// Optional commission from the next commission report.
        commission: Option<f64>,
        /// Execution ID from the CommissionReport, for correlating fills
        /// with their commission reports. `None` for fill-status events
        /// (which carry no execution ID), `Some(...)` for commission-report
        /// events.
        execution_id: Option<String>,
    },
    /// Order was cancelled.
    Cancelled {
        /// The API-assigned order ID.
        order_id: i32,
        /// Reason for cancellation, if available.
        reason: String,
    },
    /// Order went inactive (e.g., GTC expired).
    Inactive {
        /// The API-assigned order ID.
        order_id: i32,
    },
    /// Order was rejected.
    Rejected {
        /// The API-assigned order ID.
        order_id: i32,
        /// Rejection reason from IB.
        reason: String,
    },
    /// Generic status update — unknown status kind.
    Other {
        /// The API-assigned order ID.
        order_id: i32,
        /// Raw status string from IB.
        status: String,
    },
}

/// A stream of live order status updates.
///
/// Wraps an ibapi `Subscription<OrderUpdate>` and maps each item into a
/// typed [`OrderStatusEvent`]. Dropping the stream cancels the subscription.
pub struct OrderStatusStream {
    /// Inner boxed stream to hide the concrete ibapi subscription type.
    inner: BoxStream<'static, Result<ibapi::orders::OrderUpdate, ibapi::Error>>,
    /// Optional diagnostic event sender for emitting fill/rejection events.
    diagnostic_tx: Option<tokio::sync::broadcast::Sender<DiagnosticEvent>>,
}

impl OrderStatusStream {
    /// Create a new stream from an ibapi order update subscription.
    pub fn new(
        sub: ibapi::subscriptions::Subscription<ibapi::orders::OrderUpdate>,
    ) -> Self {
        Self {
            inner: sub.filter_data().boxed(),
            diagnostic_tx: None,
        }
    }

    /// Attach a diagnostic event sender for emitting fill/rejection events.
    pub fn with_diagnostics(mut self, tx: tokio::sync::broadcast::Sender<DiagnosticEvent>) -> Self {
        self.diagnostic_tx = Some(tx);
        self
    }

    /// Receive the next order status update.
    ///
    /// Returns `None` when the stream ends (connection closed / cancellation).
    pub async fn next(&mut self) -> Option<Result<OrderStatusEvent, IbError>> {
        loop {
            match self.inner.next().await {
                Some(Ok(ibapi::orders::OrderUpdate::OrderStatus(status))) => {
                    return Some(Ok(map_order_status(&status)));
                }
                Some(Ok(ibapi::orders::OrderUpdate::CommissionReport(report))) => {
                    // Commission reports are handled as part of Filled events.
                    // We emit them as separate events for consumers that want them.
                    return Some(Ok(OrderStatusEvent::Filled {
                        order_id: 0, // Not available in commission report; caller matches via execution_id
                        filled_qty: 0.0,
                        avg_price: 0.0,
                        commission: Some(report.commission),
                        execution_id: normalize_execution_id(report.execution_id),
                    }));
                }
                Some(Ok(_)) => {
                    // OpenOrder / ExecutionData — skip, handled elsewhere
                    continue;
                }
                Some(Err(e)) => return Some(Err(IbError::from(e))),
                None => return None,
            }
        }
    }
}

/// Map an ibapi [`OrderStatus`] into our typed [`OrderStatusEvent`].
fn map_order_status(status: &ibapi::orders::OrderStatus) -> OrderStatusEvent {
    let order_id = status.order_id;
    match status.status {
        OrderStatusKind::ApiPending | OrderStatusKind::ApiCancelled => {
            OrderStatusEvent::Other {
                order_id,
                status: format!("{:?}", status.status),
            }
        }
        OrderStatusKind::Submitted => OrderStatusEvent::Submitted { order_id },
        OrderStatusKind::Filled => {
            OrderStatusEvent::Filled {
                order_id,
                filled_qty: status.filled,
                avg_price: status.average_fill_price.unwrap_or(0.0),
                commission: None,
                execution_id: None,
            }
        }
        OrderStatusKind::Cancelled => OrderStatusEvent::Cancelled {
            order_id,
            reason: status.why_held.clone(),
        },
        OrderStatusKind::Inactive => OrderStatusEvent::Inactive { order_id },
        _ => OrderStatusEvent::Other {
            order_id,
            status: format!("{:?}", status.status),
        },
    }
}

/// Normalize an IB execution ID string: empty strings are coerced to `None`,
/// preserving non-empty values. This prevents `Some("")` which would force
/// every consumer to check for empty strings.
fn normalize_execution_id(s: String) -> Option<String> {
    if s.is_empty() { None } else { Some(s) }
}

impl IbClient {
    /// Submit an order to IB Gateway.
    ///
    /// Auto-assigns an order ID via [`ibapi::Client::next_valid_order_id`],
    /// then submits the order via [`ibapi::Client::submit_order`].
    ///
    /// # Returns
    /// The assigned `order_id` on successful submission. Note that IB may
    /// still reject the order asynchronously after this returns — subscribe
    /// to [`order_updates()`](Self::order_updates) to track status.
    ///
    /// # Errors
    /// Returns [`IbError::OrderRejected`] if the order ID could not be
    /// obtained or submission failed.
    pub async fn place_order(
        &self,
        contract: &Contract,
        order: &Order,
    ) -> Result<i32, IbError> {
        let order_id = self
            .inner()
            .next_valid_order_id()
            .await
            .map_err(|e| IbError::OrderRejected {
                code: 0,
                message: format!("failed to get order ID: {e}"),
                rejection_json: None,
            })?;

        self.inner()
            .submit_order(order_id, contract, order)
            .await
            .map_err(|e| IbError::OrderRejected {
                code: 0,
                message: format!("submit_order failed: {e}"),
                rejection_json: None,
            })?;

        Ok(order_id)
    }

    /// Cancel an open order by order_id.
    ///
    /// Wraps [`ibapi::Client::cancel_order`] with typed error handling.
    /// The cancellation is immediate (no manual order cancel time).
    pub async fn cancel_order(&self, order_id: i32) -> Result<(), IbError> {
        let _sub = self
            .inner()
            .cancel_order(order_id, "")
            .await
            .map_err(|e| IbError::OrderRejected {
                code: 0,
                message: format!("cancel_order failed: {e}"),
                rejection_json: None,
            })?;
        Ok(())
    }

    /// Subscribe to live order status updates.
    ///
    /// Returns a stream that yields [`OrderStatusEvent`] items until the
    /// stream is dropped or the connection is closed. Only one order update
    /// subscription can be active at a time per IB Gateway.
    pub async fn order_updates(&self) -> Result<OrderStatusStream, IbError> {
        let sub = self
            .inner()
            .order_update_stream()
            .await
            .map_err(|e| IbError::Other(format!("order_update_stream failed: {e}")))?;
        Ok(OrderStatusStream::new(sub))
    }

    /// Fetch currently open orders (one-shot snapshot).
    ///
    /// Returns a [`Vec<OpenOrder>`] of all open orders placed by this API
    /// client. Uses [`ibapi::Client::open_orders`] internally.
    pub async fn open_orders(&self) -> Result<Vec<OpenOrder>, IbError> {
        let sub = self
            .inner()
            .open_orders()
            .await
            .map_err(|e| IbError::Other(format!("open_orders failed: {e}")))?;
        let mut data = sub.filter_data();
        let mut orders = Vec::new();
        while let Some(item) = data.next().await {
            match item {
                Ok(ibapi::orders::Orders::OrderData(od)) => {
                    let order = &od.order;
                    let state = &od.order_state;
                    orders.push(OpenOrder {
                        order_id: od.order_id,
                        symbol: od.contract.symbol.0.clone(),
                        action: format!("{:?}", order.action),
                        quantity: order.total_quantity,
                        order_type: order.order_type.clone(),
                        limit_price: order.limit_price,
                        status: format!("{:?}", state.status),
                        filled_qty: order.filled_quantity,
                        remaining_qty: order.total_quantity - order.filled_quantity,
                    });
                }
                Ok(ibapi::orders::Orders::OrderStatus(_)) => {} // skip status in snapshot
                Err(e) => tracing::warn!("open_orders stream error: {e}"),
            }
        }
        Ok(orders)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::IbError;

    // ── Error propagation tests ──

    #[test]
    fn place_order_error_maps_to_order_rejected() {
        let e = IbError::OrderRejected {
            code: 0,
            message: "failed to get order ID: connection error".into(),
            rejection_json: None,
        };
        let s = e.to_string();
        assert!(s.contains("order rejection"));
        assert!(s.contains("failed to get order ID"));

        let e2 = IbError::OrderRejected {
            code: 201,
            message: "submit_order failed: insufficient funds".into(),
            rejection_json: Some("{\"reason\":\"bad\"}".into()),
        };
        let s2 = e2.to_string();
        assert!(s2.contains("201"));
        assert!(s2.contains("insufficient funds"));
    }

    #[test]
    fn place_order_returns_i32_on_success() {
        // Verify the return type is Result<i32, IbError>
        fn _check() -> Result<i32, IbError> {
            Ok(42)
        }
        assert_eq!(_check().unwrap(), 42);
    }

    // ── cancel_order tests ──

    #[test]
    fn cancel_order_error_maps_to_order_rejected() {
        let e = IbError::OrderRejected {
            code: 0,
            message: "cancel_order failed: not found".into(),
            rejection_json: None,
        };
        let s = e.to_string();
        assert!(s.contains("order rejection"));
        assert!(s.contains("cancel_order failed"));
    }

    #[test]
    fn cancel_order_success_returns_ok() {
        let result: Result<(), IbError> = Ok(());
        assert!(result.is_ok());
    }

    // ── OrderStatusEvent tests ──

    #[test]
    fn order_status_event_submitted_has_order_id() {
        let e = OrderStatusEvent::Submitted { order_id: 42 };
        assert_eq!(format!("{e:?}"), "Submitted { order_id: 42 }");
    }

    #[test]
    fn order_status_event_filled_has_qty_and_price() {
        let e = OrderStatusEvent::Filled {
            order_id: 100,
            filled_qty: 50.0,
            avg_price: 450.25,
            commission: Some(1.50),
            execution_id: None,
        };
        match e {
            OrderStatusEvent::Filled { order_id, filled_qty, avg_price, commission, .. } => {
                assert_eq!(order_id, 100);
                assert_eq!(filled_qty, 50.0);
                assert_eq!(avg_price, 450.25);
                assert_eq!(commission, Some(1.50));
            }
            _ => panic!("expected Filled variant"),
        }
    }

    #[test]
    fn order_status_event_filled_has_execution_id() {
        let e = OrderStatusEvent::Filled {
            order_id: 100,
            filled_qty: 50.0,
            avg_price: 450.25,
            commission: None,
            execution_id: Some("abc123".into()),
        };
        match e {
            OrderStatusEvent::Filled { execution_id, .. } => {
                assert_eq!(execution_id, Some("abc123".to_string()));
            }
            _ => panic!("expected Filled variant"),
        }
    }

    #[test]
    fn normalize_execution_id_coerces_empty_string() {
        assert_eq!(super::normalize_execution_id("".into()), None);
    }

    #[test]
    fn normalize_execution_id_preserves_non_empty() {
        assert_eq!(
            super::normalize_execution_id("abc123".into()),
            Some("abc123".to_string())
        );
    }

    #[test]
    fn order_status_event_cancelled_has_reason() {
        let e = OrderStatusEvent::Cancelled {
            order_id: 200,
            reason: "user requested".into(),
        };
        let s = format!("{e:?}");
        assert!(s.contains("Cancelled"));
        assert!(s.contains("user requested"));
    }

    #[test]
    fn order_status_event_rejected_has_reason() {
        let e = OrderStatusEvent::Rejected {
            order_id: 300,
            reason: "insufficient funds".into(),
        };
        let s = format!("{e:?}");
        assert!(s.contains("Rejected"));
        assert!(s.contains("insufficient funds"));
    }

    #[test]
    fn order_status_event_inactive_has_order_id() {
        let e = OrderStatusEvent::Inactive { order_id: 400 };
        assert!(format!("{e:?}").contains("Inactive"));
    }

    #[test]
    fn order_status_event_other_has_status() {
        let e = OrderStatusEvent::Other {
            order_id: 500,
            status: "ApiPending".into(),
        };
        assert!(format!("{e:?}").contains("ApiPending"));
    }

    // ── map_order_status tests ──

    #[test]
    fn map_submitted_status() {
        let status = ibapi::orders::OrderStatus {
            order_id: 1,
            status: OrderStatusKind::Submitted,
            filled: 0.0,
            remaining: 100.0,
            average_fill_price: None,
            perm_id: 0,
            parent_id: 0,
            last_fill_price: None,
            client_id: 0,
            why_held: String::new(),
            market_cap_price: None,
        };
        let event = map_order_status(&status);
        assert_eq!(event, OrderStatusEvent::Submitted { order_id: 1 });
    }

    #[test]
    fn map_filled_status() {
        let status = ibapi::orders::OrderStatus {
            order_id: 2,
            status: OrderStatusKind::Filled,
            filled: 100.0,
            remaining: 0.0,
            average_fill_price: Some(450.50),
            perm_id: 0,
            parent_id: 0,
            last_fill_price: None,
            client_id: 0,
            why_held: String::new(),
            market_cap_price: None,
        };
        let event = map_order_status(&status);
        assert_eq!(
            event,
            OrderStatusEvent::Filled {
                order_id: 2,
                filled_qty: 100.0,
                avg_price: 450.50,
                commission: None,
                execution_id: None,
            }
        );
    }

    #[test]
    fn map_cancelled_status() {
        let status = ibapi::orders::OrderStatus {
            order_id: 3,
            status: OrderStatusKind::Cancelled,
            filled: 0.0,
            remaining: 100.0,
            average_fill_price: None,
            perm_id: 0,
            parent_id: 0,
            last_fill_price: None,
            client_id: 0,
            why_held: "user cancelled".into(),
            market_cap_price: None,
        };
        let event = map_order_status(&status);
        assert_eq!(
            event,
            OrderStatusEvent::Cancelled {
                order_id: 3,
                reason: "user cancelled".into()
            }
        );
    }

    #[test]
    fn map_api_pending_is_other() {
        let status = ibapi::orders::OrderStatus {
            order_id: 4,
            status: OrderStatusKind::ApiPending,
            filled: 0.0,
            remaining: 0.0,
            average_fill_price: None,
            perm_id: 0,
            parent_id: 0,
            last_fill_price: None,
            client_id: 0,
            why_held: String::new(),
            market_cap_price: None,
        };
        let event = map_order_status(&status);
        assert!(matches!(event, OrderStatusEvent::Other { .. }));
    }

    #[test]
    fn map_inactive_status() {
        let status = ibapi::orders::OrderStatus {
            order_id: 5,
            status: OrderStatusKind::Inactive,
            filled: 0.0,
            remaining: 100.0,
            average_fill_price: None,
            perm_id: 0,
            parent_id: 0,
            last_fill_price: None,
            client_id: 0,
            why_held: String::new(),
            market_cap_price: None,
        };
        let event = map_order_status(&status);
        assert_eq!(event, OrderStatusEvent::Inactive { order_id: 5 });
    }

    #[test]
    fn order_status_stream_construct() {
        // Verify OrderStatusStream can be constructed (compile-time check)
        fn _check() {
            let _ = std::mem::size_of::<OrderStatusStream>();
        }
        _check();
    }

    // ── OpenOrder and open_orders tests ──

    #[test]
    fn open_order_struct_fields() {
        let o = OpenOrder {
            order_id: 42,
            symbol: "SPY".into(),
            action: "BUY".into(),
            quantity: 100.0,
            order_type: "LMT".into(),
            limit_price: Some(450.0),
            status: "Submitted".into(),
            filled_qty: 0.0,
            remaining_qty: 100.0,
        };
        assert_eq!(o.symbol, "SPY");
        assert_eq!(o.order_id, 42);
        assert_eq!(o.limit_price, Some(450.0));
    }

    #[test]
    fn open_order_default_limit_price() {
        let o = OpenOrder {
            order_id: 1,
            symbol: "QQQ".into(),
            action: "SELL".into(),
            quantity: 200.0,
            order_type: "MKT".into(),
            limit_price: None,
            status: "Filled".into(),
            filled_qty: 200.0,
            remaining_qty: 0.0,
        };
        assert!(o.limit_price.is_none());
        assert_eq!(o.filled_qty, o.quantity);
    }
}