Struct Subscription

Source
pub struct Subscription<'a, T: DataStream<T> + 'static> { /* private fields */ }
Expand description

Subscriptions facilitate handling responses from TWS that may be delayed or delivered periodically.

They offer both blocking and non-blocking methods for retrieving data.

In the simplest case a subscription can be implicitly converted to blocking iterator that cancels the subscription when it goes out of scope.

use ibapi::contracts::Contract;
use ibapi::market_data::realtime::{BarSize, WhatToShow};
use ibapi::Client;

let connection_url = "127.0.0.1:4002";
let client = Client::connect(connection_url, 100).expect("connection to TWS failed!");

// Request real-time bars data for AAPL with 5-second intervals
let contract = Contract::stock("AAPL");
let subscription = client
    .realtime_bars(&contract, BarSize::Sec5, WhatToShow::Trades, false)
    .expect("realtime bars request failed!");

// Use the subscription as a blocking iterator
for bar in subscription {
    // Process each bar here (e.g., print or use in calculations)
    println!("Received bar: {bar:?}");
}
// The subscription goes out of scope and is automatically cancelled.

Subscriptions can be explicitly canceled using the cancel method.

You can convert subscriptions into blocking or non-blocking iterators using the iter, try_iter or timeout_iter methods.

Alternatively, you may poll subscriptions in a blocking or non-blocking manner using the next, try_next or next_timeout methods.

Implementations§

Source§

impl<'a, T: DataStream<T> + 'static> Subscription<'a, T>

Source

pub fn next(&self) -> Option<T>

Polls the subscription for the next item and blocks until the next item is available.

This method will wait indefinitely until either:

  • A new item becomes available
  • The subscription encounters an error
  • The subscription is canceled
§Example
use ibapi::contracts::Contract;
use ibapi::market_data::realtime::{BarSize, WhatToShow};
use ibapi::Client;

let connection_url = "127.0.0.1:4002";
let client = Client::connect(connection_url, 100).expect("connection to TWS failed!");

// Request real-time bars data for AAPL with 5-second intervals
let contract = Contract::stock("AAPL");
let subscription = client
    .realtime_bars(&contract, BarSize::Sec5, WhatToShow::Trades, false)
    .expect("realtime bars request failed!");

// Process bars blocking until the next bar is available
while let Some(bar) = subscription.next() {
    println!("Received bar: {bar:?}");
}

// When the loop exits, check if it was due to an error
if let Some(err) = subscription.error() {
    eprintln!("subscription error: {err}");
}
§Returns
  • Some(T) - The next available item from the subscription
  • None - If the subscription has ended or encountered an error
Source

pub fn try_next(&self) -> Option<T>

Polls the subscription for the next item, returns immediately if no data is available.

Unlike next which blocks waiting for data, this method provides non-blocking access to the subscription data. It returns immediately with:

  • The next item if one is available
  • None if no data is currently available
  • None if an error occurred
§Example
use ibapi::contracts::Contract;
use ibapi::market_data::realtime::{BarSize, WhatToShow};
use ibapi::Client;

let connection_url = "127.0.0.1:4002";
let client = Client::connect(connection_url, 100).expect("connection to TWS failed!");

// Request real-time bars data for AAPL with 5-second intervals
let contract = Contract::stock("AAPL");
let subscription = client
    .realtime_bars(&contract, BarSize::Sec5, WhatToShow::Trades, false)
    .expect("realtime bars request failed!");

loop {
    // Process all currently available data
    while let Some(bar) = subscription.try_next() {
        println!("Received bar: {bar:?}");
    }

    // Check if we stopped due to an error
    if let Some(err) = subscription.error() {
        eprintln!("subscription error: {err}");
       break;
    }

    // No data currently available, perform other work
    // The subscription remains active and can be checked again
}
§Returns
  • Some(T) - The next available item from the subscription
  • None - If no data is immediately available or if an error occurred
Source

pub fn next_timeout(&self, timeout: Duration) -> Option<T>

Polls the subscription for the next item, waiting up to the specified timeout duration.

This method provides a middle ground between try_next and next:

  • Unlike try_next, it will wait for data to arrive
  • Unlike next, it will only wait for a specified duration
  • Returns None if no data arrives within the timeout period
§Example
use ibapi::contracts::Contract;
use ibapi::market_data::realtime::{BarSize, WhatToShow};
use ibapi::Client;
use std::time::Duration;

let connection_url = "127.0.0.1:4002";
let client = Client::connect(connection_url, 100).expect("connection to TWS failed!");

// Request real-time bars data for AAPL with 5-second intervals
let contract = Contract::stock("AAPL");
let subscription = client
    .realtime_bars(&contract, BarSize::Sec5, WhatToShow::Trades, false)
    .expect("realtime bars request failed!");

loop {
    // Wait up to 1 second for each new piece of data
    while let Some(bar) = subscription.next_timeout(Duration::from_secs(1)) {
        println!("Received bar: {bar:?}");
    }

    // Check if we stopped due to an error
    if let Some(err) = subscription.error() {
        eprintln!("subscription error: {err}");
       break;
    }

    // Either timeout occurred or no more data available
    // Perform other work before checking again
}
§Arguments
  • timeout - Maximum duration to wait for the next item
§Returns
  • Some(T) - The next available item from the subscription
  • None - If no data arrives within the timeout period or if an error occurred
§See also
Source

pub fn cancel(&self)

Cancel the subscription

Source

pub fn iter(&self) -> SubscriptionIter<'_, T>

Creates an iterator from the Subscription that blocks until the next item is available.

The iterator does not consume the Subscription, allowing you to explicitly cancel the subscription at any time using the cancel method.

§Example
use ibapi::contracts::Contract;
use ibapi::market_data::realtime::{BarSize, WhatToShow};
use ibapi::Client;

let connection_url = "127.0.0.1:4002";
let client = Client::connect(connection_url, 100).expect("connection to TWS failed!");

// Request real-time bars data for AAPL with 5-second intervals
let contract = Contract::stock("AAPL");
let subscription = client
    .realtime_bars(&contract, BarSize::Sec5, WhatToShow::Trades, false)
    .expect("realtime bars request failed!");

// Create an iterator that blocks until the next item is available.
for bar in subscription.iter() {
    // Process each bar here (e.g., print or use in calculations)
    println!("Received bar: {bar:?}");
}
// The subscription is still in scope and can be explicitly canceled.
§Returns

A SubscriptionIter that yields items as they become available, blocking if necessary.

Source

pub fn try_iter(&self) -> SubscriptionTryIter<'_, T>

Creates an iterator from the Subscription that returns the next bar if available without waiting.

The iterator does not consume the Subscription, allowing you to explicitly cancel the subscription at any time using the cancel method.

§Example
use ibapi::contracts::Contract;
use ibapi::market_data::realtime::{BarSize, WhatToShow};
use ibapi::Client;
use std::thread;
use std::time::Duration;

let connection_url = "127.0.0.1:4002";
let client = Client::connect(connection_url, 100).expect("connection to TWS failed!");

// Request real-time bars data for AAPL with 5-second intervals
let contract = Contract::stock("AAPL");
let subscription = client
    .realtime_bars(&contract, BarSize::Sec5, WhatToShow::Trades, false)
    .expect("realtime bars request failed!");

// Process data in a non-blocking way.
loop {
    // Create an iterator that returns the next bar without waiting.
    for bar in subscription.try_iter() {
        // Process all available data here.
    }

    // Perform other work between checking for data.
    // The subscription remains active and can be cancelled when needed.

    // Optional: Add a small delay to prevent excessive CPU usage
    thread::sleep(Duration::from_secs(1));
}
§Returns

A SubscriptionTryIter that yields items if they are available, without waiting.

Source

pub fn timeout_iter(&self, timeout: Duration) -> SubscriptionTimeoutIter<'_, T>

Creates an iterator from the Subscription that waits until specified timeout for available data.

Similar to try_iter, this iterator does not consume the Subscription, allowing you to explicitly cancel the subscription at any time using the cancel method. However, unlike try_iter which returns immediately, this iterator will wait up to the specified timeout duration before yielding data or returning.

§Example
use ibapi::contracts::Contract;
use ibapi::market_data::realtime::{BarSize, WhatToShow};
use ibapi::Client;
use std::thread;
use std::time::Duration;

let connection_url = "127.0.0.1:4002";
let client = Client::connect(connection_url, 100).expect("connection to TWS failed!");

// Request real-time bars data for AAPL with 5-second intervals
let contract = Contract::stock("AAPL");
let subscription = client
    .realtime_bars(&contract, BarSize::Sec5, WhatToShow::Trades, false)
    .expect("realtime bars request failed!");

// Process data with a 1-second timeout between checks
loop {
    // Iterator will wait up to 1 second for new data before continuing
    for bar in subscription.timeout_iter(Duration::from_secs(1)) {
        // Process all available data here.
    }

    // If no data arrives within timeout, loop continues here
    // Perform other work between checking for data.
    // The subscription remains active and can be cancelled when needed.
}
§Arguments
  • timeout - Maximum duration to wait for data before continuing iteration
§Returns

A SubscriptionTimeoutIter that waits for the specified timeout duration for available data.

Source

pub fn error(&self) -> Option<Error>

Returns any error that caused the Subscription to stop receiving data.

A Subscription may stop yielding items either because there is no more data available or because it encountered an error condition (e.g., network disconnection). This method allows checking if an error occurred and retrieving the error details.

§Returns
  • Some(Error) - If an error occurred that stopped the subscription
  • None - If no error has occurred (subscription may still be active or completed normally)

Trait Implementations§

Source§

impl<'a, T: Debug + DataStream<T> + 'static> Debug for Subscription<'a, T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: DataStream<T> + 'static> Drop for Subscription<'_, T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<'a, T: DataStream<T> + 'static> IntoIterator for &'a Subscription<'a, T>

Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = SubscriptionIter<'a, T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, T: DataStream<T> + 'static> IntoIterator for Subscription<'a, T>

Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = SubscriptionOwnedIter<'a, T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl SharesChannel for Subscription<'_, NewsBulletin>

Source§

impl SharesChannel for Subscription<'_, PositionUpdate>

Auto Trait Implementations§

§

impl<'a, T> !Freeze for Subscription<'a, T>

§

impl<'a, T> !RefUnwindSafe for Subscription<'a, T>

§

impl<'a, T> Send for Subscription<'a, T>
where T: Send,

§

impl<'a, T> Sync for Subscription<'a, T>
where T: Sync,

§

impl<'a, T> Unpin for Subscription<'a, T>
where T: Unpin,

§

impl<'a, T> !UnwindSafe for Subscription<'a, T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.