Subscription

Struct Subscription 

Source
pub struct Subscription<T: StreamDecoder<T>> { /* private fields */ }
Expand description

A Subscription is a stream of responses returned from TWS. A Subscription is normally returned when invoking an API that can return more than one value.

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<T: StreamDecoder<T>> Subscription<T>

Source

pub fn cancel(&self)

Cancel the subscription

Source

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

Returns the next available value, blocking if necessary until a value becomes available.

§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;

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

let contract = Contract::stock("AAPL").build();
let subscription = client.market_data(&contract)
    .generic_ticks(&["233"])
    .subscribe()
    .expect("market data request failed");

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

// 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 error(&self) -> Option<Error>

Returns the current error state of the subscription.

This method allows checking if an error occurred during subscription processing. Errors are stored internally when they occur during next(), try_next(), or next_timeout() calls.

§Returns
  • Some(Error) - If an error has occurred
  • None - If no error has occurred
Source

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

Tries to return the next available value without blocking.

Returns immediately with:

  • Some(value) if a value is available
  • None if no data is currently available

Use this method when you want to poll for data without blocking. Check error() to determine if None was returned due to an error.

§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use std::thread;
use std::time::Duration;

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

let contract = Contract::stock("AAPL").build();
let subscription = client.market_data(&contract)
    .generic_ticks(&["233"])
    .subscribe()
    .expect("market data request failed");

// Poll for data without blocking
loop {
    if let Some(data) = subscription.try_next() {
        println!("{data:?}");
    } else if let Some(err) = subscription.error() {
        eprintln!("Error: {err}");
        break;
    } else {
        // No data available, do other work or sleep
        thread::sleep(Duration::from_millis(100));
    }
}
Source

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

Waits for the next available value up to the specified timeout duration.

Returns:

  • Some(value) if a value becomes available within the timeout
  • None if the timeout expires before data becomes available

Check error() to determine if None was returned due to an error.

§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use std::time::Duration;

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

let contract = Contract::stock("AAPL").build();
let subscription = client.market_data(&contract)
    .generic_ticks(&["233"])
    .subscribe()
    .expect("market data request failed");

// Wait up to 5 seconds for data
if let Some(data) = subscription.next_timeout(Duration::from_secs(5)) {
    println!("{data:?}");
} else if let Some(err) = subscription.error() {
    eprintln!("Error: {err}");
} else {
    eprintln!("Timeout: no data received within 5 seconds");
}
Source

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

Creates a blocking iterator over the subscription data.

The iterator will block waiting for the next value if none is immediately available. The iterator ends when the subscription is cancelled or an unrecoverable error occurs.

§Examples
use ibapi::client::blocking::Client;

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

let subscription = client.positions().expect("positions request failed");

// Process all positions as they arrive
for position in subscription.iter() {
    println!("{position:?}");
}

// Check if iteration ended due to an error
if let Some(err) = subscription.error() {
    eprintln!("Subscription error: {err}");
}
Source

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

Creates a non-blocking iterator over the subscription data.

The iterator will return immediately with None if no data is available. Use this when you want to process available data without blocking.

§Examples
use ibapi::client::blocking::Client;
use std::thread;
use std::time::Duration;

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

let subscription = client.positions().expect("positions request failed");

// Process available positions without blocking
loop {
    let mut data_received = false;
    for position in subscription.try_iter() {
        data_received = true;
        println!("{position:?}");
    }
     
    if let Some(err) = subscription.error() {
        eprintln!("Error: {err}");
        break;
    }
     
    if !data_received {
        // No data available, do other work or sleep
        thread::sleep(Duration::from_millis(100));
    }
}
Source

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

Creates an iterator that waits up to the specified timeout for each value.

The iterator will wait up to timeout duration for each value. If the timeout expires, the iterator ends.

§Examples
use ibapi::client::blocking::Client;
use std::time::Duration;

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

let subscription = client.positions().expect("positions request failed");

// Process positions with a 5 second timeout per item
for position in subscription.timeout_iter(Duration::from_secs(5)) {
    println!("{position:?}");
}

if let Some(err) = subscription.error() {
    eprintln!("Error: {err}");
} else {
    println!("No more positions received within timeout");
}

Trait Implementations§

Source§

impl<T: StreamDecoder<T>> Drop for Subscription<T>

Source§

fn drop(&mut self)

Cancel subscription on drop

Source§

impl<'a, T: StreamDecoder<T>> IntoIterator for &'a Subscription<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<T: StreamDecoder<T>> IntoIterator for Subscription<T>

Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = SubscriptionOwnedIter<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<T> !Freeze for Subscription<T>

§

impl<T> !RefUnwindSafe for Subscription<T>

§

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

§

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

§

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

§

impl<T> !UnwindSafe for Subscription<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.