Skip to main content

ClientConfig

Struct ClientConfig 

Source
pub struct ClientConfig {
    pub host: String,
    pub port: u16,
    pub client_id: i32,
    pub connect_options: Option<String>,
    pub optional_capabilities: Option<String>,
    pub prefer_protobuf: bool,
}
Expand description

TWS/Gateway client configuration.

Fields§

§host: String

Host name or IP address. Empty values are normalized to 127.0.0.1.

§port: u16

TWS/Gateway socket port.

§client_id: i32

TWS API client id.

§connect_options: Option<String>

Optional connect options appended to the enhanced handshake version string.

§optional_capabilities: Option<String>

Optional capabilities sent by start_api when supported by the server.

§prefer_protobuf: bool

Whether to use the IB protobuf extension after startApi. Some local Gateway deployments negotiate a modern version but reject jextend.

Implementations§

Source§

impl ClientConfig

Source

pub fn new(host: impl Into<String>, port: u16, client_id: i32) -> Self

Creates a new configuration.

Examples found in repository?
examples/twsapi/main.rs (line 517)
513async fn connect() -> Result<TwsApiClient, CliError> {
514    let host = env_string("TWS_HOST", "127.0.0.1");
515    let port = env_parse("TWS_PORT", 7497u16)?;
516    let client_id = env_parse("TWS_CLIENT_ID", 1002i32)?;
517    Ok(TwsApiClient::connect(ClientConfig::new(host, port, client_id)).await?)
518}
More examples
Hide additional examples
examples/request_current_time.rs (line 16)
5async fn main() -> truefix_twsapi_client::error::TwsApiResult<()> {
6    let host = std::env::var("TWS_HOST").unwrap_or_else(|_| "127.0.0.1".to_owned());
7    let port = std::env::var("TWS_PORT")
8        .ok()
9        .and_then(|value| value.parse::<u16>().ok())
10        .unwrap_or(7497);
11    let client_id = std::env::var("TWS_CLIENT_ID")
12        .ok()
13        .and_then(|value| value.parse::<i32>().ok())
14        .unwrap_or(1001);
15
16    let mut client = TwsApiClient::connect(ClientConfig::new(host, port, client_id)).await?;
17    client.req_current_time().await?;
18
19    loop {
20        match client.read_event().await? {
21            Event::CurrentTime { time } => {
22                println!("{time}");
23                break;
24            }
25            Event::Error { code, message, .. } => {
26                eprintln!("TWS error {code}: {message}");
27                break;
28            }
29            _ => {}
30        }
31    }
32
33    Ok(())
34}
examples/request_market_data.rs (line 28)
9async fn main() -> truefix_twsapi_client::error::TwsApiResult<()> {
10    let host = std::env::var("TWS_HOST").unwrap_or_else(|_| "127.0.0.1".to_owned());
11    let port = std::env::var("TWS_PORT")
12        .ok()
13        .and_then(|value| value.parse::<u16>().ok())
14        .unwrap_or(7497);
15    let client_id = std::env::var("TWS_CLIENT_ID")
16        .ok()
17        .and_then(|value| value.parse::<i32>().ok())
18        .unwrap_or(1002);
19    let symbol = std::env::var("TWS_SYMBOL").unwrap_or_else(|_| "AAPL".to_owned());
20    let exchange = std::env::var("TWS_EXCHANGE").unwrap_or_else(|_| "SMART".to_owned());
21    let currency = std::env::var("TWS_CURRENCY").unwrap_or_else(|_| "USD".to_owned());
22    let market_data_type = std::env::var("TWS_MARKET_DATA_TYPE")
23        .ok()
24        .and_then(|value| value.parse::<i32>().ok())
25        .unwrap_or(1);
26
27    let req_id = 9001;
28    let mut client = TwsApiClient::connect(ClientConfig::new(host, port, client_id)).await?;
29    wait_until_api_ready(&mut client).await?;
30    client.req_market_data_type(market_data_type).await?;
31    client
32        .req_mkt_data(MarketDataRequest {
33            req_id,
34            contract: Contract {
35                symbol,
36                sec_type: "STK".to_owned(),
37                exchange,
38                currency,
39                ..Contract::default()
40            },
41            generic_tick_list: String::new(),
42            snapshot: false,
43            regulatory_snapshot: false,
44            market_data_options: Vec::new(),
45        })
46        .await?;
47
48    let result = tokio::time::timeout(Duration::from_secs(30), async {
49        let should_cancel = loop {
50            match client.read_event().await? {
51                Event::TickPrice {
52                    req_id: event_req_id,
53                    tick_type,
54                    price,
55                    attrib,
56                } if event_req_id == req_id => {
57                    println!("price tick_type={tick_type} price={price} attrib={attrib}");
58                    break true;
59                }
60                Event::TickSize {
61                    req_id: event_req_id,
62                    tick_type,
63                    size,
64                } if event_req_id == req_id => {
65                    println!("size tick_type={tick_type} size={size}");
66                }
67                Event::Error {
68                    req_id: event_req_id,
69                    code,
70                    message,
71                    ..
72                } if event_req_id < 0 && is_market_data_status_code(code) => {
73                    eprintln!("TWS status {code}: {message}");
74                }
75                Event::Error {
76                    req_id: event_req_id,
77                    code,
78                    message,
79                    ..
80                } if event_req_id == req_id && is_delayed_market_data_notice(code) => {
81                    eprintln!("TWS notice {code}: {message}");
82                }
83                Event::Error {
84                    req_id: event_req_id,
85                    code,
86                    message,
87                    ..
88                } if event_req_id == req_id => {
89                    eprintln!("TWS error {code}: {message}");
90                    break false;
91                }
92                Event::Error { code, message, .. } => {
93                    eprintln!("TWS notice {code}: {message}");
94                }
95                _ => {}
96            }
97        };
98        truefix_twsapi_client::error::TwsApiResult::Ok(should_cancel)
99    })
100    .await;
101
102    let should_cancel = match &result {
103        Ok(Ok(should_cancel)) => *should_cancel,
104        Ok(Err(_)) | Err(_) => true,
105    };
106    if should_cancel && let Err(error) = client.cancel_mkt_data(req_id).await {
107        eprintln!("cancelMktData failed: {error}");
108    }
109    if should_cancel {
110        tokio::time::sleep(Duration::from_millis(250)).await;
111    }
112
113    match result {
114        Ok(result) => result.map(|_| ()),
115        Err(_) => {
116            eprintln!("timed out waiting for market data");
117            Ok(())
118        }
119    }
120}

Trait Implementations§

Source§

impl Clone for ClientConfig

Source§

fn clone(&self) -> ClientConfig

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ClientConfig

Source§

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

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

impl Eq for ClientConfig

Source§

impl PartialEq for ClientConfig

Source§

fn eq(&self, other: &ClientConfig) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for ClientConfig

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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.