ibkr_cp_api_client/
client.rs

1use std::env;
2
3/// This is the base class of the library. It is used to communicate with the IB CP Gateway.
4///
5/// https://interactivebrokers.github.io/cpwebapi/endpoints
6///
7/// bin/run.sh root/conf.yaml
8#[derive(Debug, Default, Clone)]
9pub struct IBClientPortal {
10    pub port: i32,
11    pub listen_ssl: bool,
12    pub account: String,
13    pub client: reqwest::Client,
14    pub session_id: Option<String>,
15}
16impl IBClientPortal {
17    pub fn new(port: i32, listen_ssl: bool, account: &str) -> IBClientPortal {
18        let mut default_headers = reqwest::header::HeaderMap::new();
19        default_headers.insert(
20            reqwest::header::CONTENT_TYPE,
21            reqwest::header::HeaderValue::from_static("application/json"),
22        );
23        default_headers.insert(
24            reqwest::header::USER_AGENT,
25            reqwest::header::HeaderValue::from_static("Console"),
26        );
27        let client = reqwest::Client::builder()
28            .danger_accept_invalid_certs(true)
29            .default_headers(default_headers)
30            .timeout(std::time::Duration::from_secs(5))
31            .build()
32            .unwrap();
33        IBClientPortal {
34            port,
35            client,
36            listen_ssl,
37            account: account.to_string(),
38            session_id: None,
39        }
40    }
41    ///Builds the client from env vars. Needs
42    /// `IB_PORT`
43    /// `IB_SSL`
44    /// `IB_ACCOUNT`
45    pub fn from_env() -> Self {
46        dotenvy::dotenv().ok();
47        let port = env::var("IB_PORT")
48            .expect("IB_PORT must be set")
49            .parse()
50            .unwrap();
51        let listen_ssl = env::var("IB_SSL").unwrap_or_default().parse().unwrap();
52        let account = env::var("IB_ACCOUNT").expect("IB_ACCOUNT must be set");
53        IBClientPortal::new(port, listen_ssl, &account)
54    }
55}