Skip to main content

nautilus_interactive_brokers/gateway/
dockerized.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Dockerized IB Gateway management.
17
18#[cfg(feature = "gateway")]
19use std::{collections::HashMap, fmt::Debug, time::Duration};
20
21#[cfg(feature = "gateway")]
22use anyhow::Context;
23#[cfg(feature = "gateway")]
24use bollard::Docker;
25#[cfg(feature = "gateway")]
26use bollard::container::LogOutput;
27#[cfg(feature = "gateway")]
28use bollard::models::{
29    ContainerCreateBody, ContainerCreateResponse, HostConfig, PortBinding, RestartPolicy,
30    RestartPolicyNameEnum,
31};
32#[cfg(feature = "gateway")]
33use bollard::query_parameters::{
34    CreateContainerOptions, ListContainersOptions, LogsOptions, RemoveContainerOptions,
35    StartContainerOptions, StopContainerOptions,
36};
37#[cfg(feature = "gateway")]
38use futures_util::StreamExt;
39#[cfg(feature = "gateway")]
40use jiff::Timestamp;
41#[cfg(feature = "gateway")]
42use nautilus_core::string::secret::SecretString;
43use serde::{Deserialize, Serialize};
44
45#[cfg(not(feature = "gateway"))]
46use crate::config::DockerizedIBGatewayConfig;
47#[cfg(feature = "gateway")]
48use crate::config::{DockerizedIBGatewayConfig, TradingMode};
49
50/// Container status enumeration.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
52#[cfg_attr(
53    feature = "python",
54    pyo3::pyclass(
55        module = "nautilus_trader.adapters.interactive_brokers",
56        from_py_object,
57        rename_all = "SCREAMING_SNAKE_CASE"
58    )
59)]
60#[cfg_attr(
61    feature = "python",
62    pyo3_stub_gen::derive::gen_stub_pyclass_enum(
63        module = "nautilus_trader.adapters.interactive_brokers"
64    )
65)]
66pub enum ContainerStatus {
67    /// No container exists.
68    NoContainer = 1,
69    /// Container has been created but not started.
70    ContainerCreated = 2,
71    /// Container is starting.
72    ContainerStarting = 3,
73    /// Container has stopped.
74    ContainerStopped = 4,
75    /// Container is running but not logged in.
76    NotLoggedIn = 5,
77    /// Container is ready (running and logged in).
78    Ready = 6,
79    /// Unknown container status.
80    Unknown = 7,
81}
82
83/// Dockerized IB Gateway manager.
84///
85/// This struct manages the lifecycle of Interactive Brokers Gateway Docker containers,
86/// including creation, starting, stopping, and status checking.
87#[derive(Clone)]
88#[cfg_attr(
89    feature = "python",
90    pyo3::pyclass(
91        module = "nautilus_trader.adapters.interactive_brokers",
92        from_py_object
93    )
94)]
95#[cfg_attr(
96    feature = "python",
97    pyo3_stub_gen::derive::gen_stub_pyclass(
98        module = "nautilus_trader.adapters.interactive_brokers"
99    )
100)]
101#[cfg(feature = "gateway")]
102pub struct DockerizedIBGateway {
103    /// Configuration for the gateway.
104    config: DockerizedIBGatewayConfig,
105    /// Docker client.
106    pub(crate) docker: Docker,
107    /// Username for IB account.
108    username: SecretString,
109    /// Password for IB account.
110    password: SecretString,
111    /// Host address (always 127.0.0.1).
112    host: String,
113    /// Port for the gateway.
114    port: u16,
115    /// Container name.
116    container_name: String,
117}
118
119#[cfg(feature = "gateway")]
120impl Debug for DockerizedIBGateway {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        f.debug_struct(stringify!(DockerizedIBGateway))
123            .field("host", &self.host)
124            .field("port", &self.port)
125            .field("container_name", &self.container_name)
126            .field("trading_mode", &self.config.trading_mode)
127            .finish_non_exhaustive()
128    }
129}
130
131#[cfg(feature = "gateway")]
132impl DockerizedIBGateway {
133    /// Base container name.
134    pub const CONTAINER_NAME: &'static str = "nautilus-ib-gateway";
135
136    /// Host API ports by trading mode.
137    pub const HOST_PORTS: &'static [(&'static str, u16)] = &[("Paper", 4002), ("Live", 4001)];
138
139    /// Container API ports exposed by the IB Gateway image.
140    pub const CONTAINER_PORTS: &'static [(&'static str, u16)] = &[("Paper", 4004), ("Live", 4003)];
141
142    /// Internal VNC port.
143    pub const VNC_PORT_INTERNAL: u16 = 5900;
144
145    fn host_port_for_mode(trading_mode: TradingMode) -> u16 {
146        match trading_mode {
147            TradingMode::Paper => 4002,
148            TradingMode::Live => 4001,
149        }
150    }
151
152    fn container_port_for_mode(trading_mode: TradingMode) -> u16 {
153        match trading_mode {
154            TradingMode::Paper => 4004,
155            TradingMode::Live => 4003,
156        }
157    }
158
159    fn logs_indicate_ready(logs: &str) -> bool {
160        logs.contains("Login has completed")
161            || logs.contains("Configuration tasks completed")
162            || logs.contains("Logged in to")
163            || logs.contains("Login successful")
164    }
165
166    fn session_logs_indicate_ready(logs: &str, started_at: Timestamp) -> bool {
167        logs.lines().any(|line| {
168            let Some((timestamp, message)) = line.split_once(' ') else {
169                return false;
170            };
171
172            timestamp.parse::<Timestamp>().is_ok_and(|timestamp| {
173                timestamp >= started_at && Self::logs_indicate_ready(message)
174            })
175        })
176    }
177
178    /// Create a new DockerizedIBGateway from configuration.
179    ///
180    /// # Errors
181    ///
182    /// Returns an error if:
183    /// - Username or password is not provided and not available in environment variables.
184    /// - Docker client creation fails.
185    pub fn new(mut config: DockerizedIBGatewayConfig) -> anyhow::Result<Self> {
186        let username = config
187            .username
188            .take()
189            .or_else(|| std::env::var("TWS_USERNAME").ok().map(SecretString::from))
190            .ok_or_else(|| anyhow::anyhow!("username not set nor available in env TWS_USERNAME"))?;
191
192        let password = config
193            .password
194            .take()
195            .or_else(|| std::env::var("TWS_PASSWORD").ok().map(SecretString::from))
196            .ok_or_else(|| anyhow::anyhow!("password not set nor available in env TWS_PASSWORD"))?;
197
198        // Connect to Docker
199        let docker = Docker::connect_with_local_defaults().context(
200            "Failed to connect to the local Docker daemon. Ensure Docker is running and the local Docker socket is available",
201        )?;
202
203        // Determine port based on trading mode
204        let mode_str = match config.trading_mode {
205            TradingMode::Paper => "Paper",
206            TradingMode::Live => "Live",
207        };
208
209        let port = Self::host_port_for_mode(config.trading_mode);
210
211        // Generate container name
212        let container_name = format!("{}-{}", Self::CONTAINER_NAME, mode_str).to_lowercase();
213
214        Ok(Self {
215            config,
216            docker,
217            username,
218            password,
219            host: "127.0.0.1".to_string(),
220            port,
221            container_name,
222        })
223    }
224
225    /// Get the container name.
226    pub fn container_name(&self) -> &str {
227        &self.container_name
228    }
229
230    /// Get the host address.
231    pub fn host(&self) -> &str {
232        &self.host
233    }
234
235    /// Get the port.
236    pub fn port(&self) -> u16 {
237        self.port
238    }
239
240    /// Check if the container is logged in by examining logs.
241    ///
242    /// # Errors
243    ///
244    /// Returns an error if log retrieval fails.
245    pub async fn is_logged_in(&self, container_id: &str) -> anyhow::Result<bool> {
246        let started_at = self
247            .docker
248            .inspect_container(container_id, None)
249            .await
250            .context("Failed to inspect gateway container")?
251            .state
252            .and_then(|state| state.started_at)
253            .context("Gateway container start time is missing")?
254            .parse::<Timestamp>()
255            .context("Gateway container start time is invalid")?;
256        let since = i32::try_from(started_at.as_second())
257            .context("Gateway container start time exceeds the Docker log API range")?;
258
259        let logs_options = LogsOptions {
260            stdout: true,
261            stderr: true,
262            since,
263            timestamps: true,
264            ..Default::default()
265        };
266
267        let mut logs_stream = self.docker.logs(container_id, Some(logs_options));
268
269        let mut logged_in = false;
270
271        while let Some(log_result) = logs_stream.next().await {
272            let log_output = log_result.context("Failed to read log chunk")?;
273
274            // Handle LogOutput enum variants
275            let log_bytes = match log_output {
276                LogOutput::StdOut { message } | LogOutput::StdErr { message } => message,
277                LogOutput::StdIn { message } | LogOutput::Console { message } => message,
278            };
279
280            let log_string = String::from_utf8_lossy(&log_bytes);
281            if Self::session_logs_indicate_ready(&log_string, started_at) {
282                logged_in = true;
283                break;
284            }
285        }
286
287        Ok(logged_in)
288    }
289
290    /// Get the current container status.
291    ///
292    /// # Errors
293    ///
294    /// Returns an error if container inspection fails.
295    pub async fn container_status(&self) -> anyhow::Result<ContainerStatus> {
296        let list_options = ListContainersOptions {
297            all: true,
298            ..Default::default()
299        };
300
301        let containers = self
302            .docker
303            .list_containers(Some(list_options))
304            .await
305            .context("Failed to list containers")?;
306
307        let container = containers.iter().find(|c| {
308            c.names
309                .as_ref()
310                .and_then(|names| names.first())
311                .is_some_and(|name| name.trim_start_matches('/') == self.container_name)
312        });
313
314        let Some(container) = container else {
315            return Ok(ContainerStatus::NoContainer);
316        };
317
318        let state = container
319            .state
320            .as_ref()
321            .map_or("unknown", |state| state.as_ref());
322
323        match state {
324            "running" => {
325                let container_id = container
326                    .id
327                    .as_ref()
328                    .ok_or_else(|| anyhow::anyhow!("Container ID missing"))?;
329
330                if self.is_logged_in(container_id).await.unwrap_or(false) {
331                    Ok(ContainerStatus::Ready)
332                } else {
333                    Ok(ContainerStatus::ContainerStarting)
334                }
335            }
336            "stopped" | "exited" => Ok(ContainerStatus::ContainerStopped),
337            "created" => Ok(ContainerStatus::ContainerCreated),
338            _ => Ok(ContainerStatus::Unknown),
339        }
340    }
341
342    /// Start the gateway container.
343    ///
344    /// # Errors
345    ///
346    /// Returns an error if container creation or startup fails.
347    pub async fn start(&mut self, wait: Option<u64>) -> anyhow::Result<()> {
348        tracing::debug!("Ensuring gateway is running");
349
350        let status = self.container_status().await?;
351
352        let broken_statuses = [
353            ContainerStatus::NotLoggedIn,
354            ContainerStatus::ContainerStopped,
355            ContainerStatus::ContainerCreated,
356            ContainerStatus::Unknown,
357        ];
358
359        match status {
360            ContainerStatus::NoContainer => {
361                tracing::debug!("No container, starting");
362            }
363            status if broken_statuses.contains(&status) => {
364                tracing::debug!("Status {:?}, removing existing container", status);
365                self.stop().await?;
366            }
367            ContainerStatus::Ready | ContainerStatus::ContainerStarting => {
368                tracing::debug!("Status {:?}, using existing container", status);
369                return Ok(());
370            }
371            _ => {}
372        }
373
374        tracing::debug!("Starting new container");
375
376        // Determine port mappings
377        let host_port = Self::host_port_for_mode(self.config.trading_mode);
378        let container_port = Self::container_port_for_mode(self.config.trading_mode);
379
380        let mut port_bindings = HashMap::new();
381        port_bindings.insert(
382            format!("{container_port}/tcp"),
383            Some(vec![PortBinding {
384                host_ip: Some(self.host.clone()),
385                host_port: Some(host_port.to_string()),
386            }]),
387        );
388
389        if let Some(vnc_port) = self.config.vnc_port {
390            port_bindings.insert(
391                format!("{}/tcp", Self::VNC_PORT_INTERNAL),
392                Some(vec![PortBinding {
393                    host_ip: Some(self.host.clone()),
394                    host_port: Some(vnc_port.to_string()),
395                }]),
396            );
397        }
398
399        // Prepare environment variables
400        let mode_str = match self.config.trading_mode {
401            TradingMode::Paper => "paper",
402            TradingMode::Live => "live",
403        };
404
405        let env = vec![
406            format!("TWS_USERID={}", self.username.expose_secret()),
407            format!("TWS_PASSWORD={}", self.password.expose_secret()),
408            format!("TRADING_MODE={}", mode_str),
409            format!(
410                "READ_ONLY_API={}",
411                if self.config.read_only_api {
412                    "yes"
413                } else {
414                    "no"
415                }
416            ),
417            "EXISTING_SESSION_DETECTED_ACTION=primary".to_string(),
418        ];
419
420        // Create container configuration
421        let container_config = ContainerCreateBody {
422            image: Some(self.config.container_image.clone()),
423            hostname: Some(self.container_name.clone()),
424            host_config: Some(HostConfig {
425                port_bindings: Some(port_bindings),
426                restart_policy: Some(RestartPolicy {
427                    name: Some(RestartPolicyNameEnum::ALWAYS),
428                    maximum_retry_count: None,
429                }),
430                ..Default::default()
431            }),
432            env: Some(env),
433            ..Default::default()
434        };
435
436        // Create container
437        let create_options = CreateContainerOptions {
438            name: Some(self.container_name.clone()),
439            ..Default::default()
440        };
441
442        let create_response: ContainerCreateResponse = self
443            .docker
444            .create_container(Some(create_options), container_config)
445            .await
446            .context("Failed to create container")?;
447
448        let container_id = create_response.id;
449
450        // Start container
451        self.docker
452            .start_container(&container_id, None::<StartContainerOptions>)
453            .await
454            .context("Failed to start container")?;
455
456        tracing::debug!(
457            "Container `{}` starting, waiting for ready",
458            self.container_name
459        );
460
461        // Wait for container to be ready
462        let wait_time = wait.unwrap_or(self.config.timeout);
463        let mut waited = 0u64;
464
465        while waited < wait_time {
466            if self.is_logged_in(&container_id).await.unwrap_or(false) {
467                tracing::debug!(
468                    "Gateway `{}` ready. VNC port is {:?}",
469                    self.container_name,
470                    self.config.vnc_port
471                );
472                return Ok(());
473            }
474
475            tracing::debug!("Waiting for IB Gateway to start");
476            tokio::time::sleep(Duration::from_secs(1)).await;
477            waited += 1;
478        }
479
480        anyhow::bail!(
481            "Gateway `{}` not ready after {} seconds",
482            self.container_name,
483            wait_time
484        )
485    }
486
487    /// Safely start the gateway, handling container already exists errors.
488    ///
489    /// # Errors
490    ///
491    /// Returns an error if startup fails (other than container exists).
492    pub async fn safe_start(&mut self, wait: Option<u64>) -> anyhow::Result<()> {
493        match self.start(wait).await {
494            Ok(()) => Ok(()),
495            Err(e) if e.to_string().contains("already exists") => {
496                tracing::warn!("Container already exists, continuing");
497                Ok(())
498            }
499            Err(e) => Err(e),
500        }
501    }
502
503    /// Stop and remove the gateway container.
504    ///
505    /// # Errors
506    ///
507    /// Returns an error if container stop or removal fails.
508    pub async fn stop(&self) -> anyhow::Result<()> {
509        let list_options = ListContainersOptions {
510            all: true,
511            ..Default::default()
512        };
513
514        let containers = self
515            .docker
516            .list_containers(Some(list_options))
517            .await
518            .context("Failed to list containers")?;
519
520        let container = containers.iter().find(|c| {
521            c.names
522                .as_ref()
523                .and_then(|names| names.first())
524                .is_some_and(|name| name.trim_start_matches('/') == self.container_name)
525        });
526
527        if let Some(container) = container
528            && let Some(container_id) = &container.id
529        {
530            // Stop container if running
531            if matches!(
532                container.state.as_ref().map(|state| state.as_ref()),
533                Some("running")
534            ) {
535                self.docker
536                    .stop_container(container_id, None::<StopContainerOptions>)
537                    .await
538                    .context("Failed to stop container")?;
539            }
540
541            // Remove container
542            let remove_options = RemoveContainerOptions {
543                force: true,
544                ..Default::default()
545            };
546
547            self.docker
548                .remove_container(container_id, Some(remove_options))
549                .await
550                .context("Failed to remove container")?;
551
552            tracing::debug!("Stopped and removed container `{}`", self.container_name);
553        }
554
555        Ok(())
556    }
557}
558
559/// Stub implementation when gateway feature is disabled.
560#[cfg(not(feature = "gateway"))]
561#[derive(Debug)]
562pub struct DockerizedIBGateway;
563
564#[cfg(not(feature = "gateway"))]
565impl DockerizedIBGateway {
566    /// # Errors
567    ///
568    /// Returns an error if the Dockerized IB Gateway cannot be created or started.
569    pub fn new(_config: DockerizedIBGatewayConfig) -> anyhow::Result<Self> {
570        anyhow::bail!("Gateway feature is not enabled. Build with --features gateway")
571    }
572}
573
574#[cfg(all(test, feature = "gateway"))]
575mod tests {
576    use jiff::Timestamp;
577    use nautilus_core::string::secret::SecretString;
578    use rstest::rstest;
579
580    use super::DockerizedIBGateway;
581    use crate::config::{DockerizedIBGatewayConfig, TradingMode};
582
583    #[rstest]
584    #[case(TradingMode::Paper, 4002)]
585    #[case(TradingMode::Live, 4001)]
586    fn host_port_matches_trading_mode(#[case] trading_mode: TradingMode, #[case] expected: u16) {
587        assert_eq!(
588            DockerizedIBGateway::host_port_for_mode(trading_mode),
589            expected
590        );
591    }
592
593    #[rstest]
594    #[case(TradingMode::Paper, 4004)]
595    #[case(TradingMode::Live, 4003)]
596    fn container_port_matches_trading_mode(
597        #[case] trading_mode: TradingMode,
598        #[case] expected: u16,
599    ) {
600        assert_eq!(
601            DockerizedIBGateway::container_port_for_mode(trading_mode),
602            expected
603        );
604    }
605
606    #[rstest]
607    #[case(TradingMode::Paper, 4002)]
608    #[case(TradingMode::Live, 4001)]
609    fn new_reports_the_host_api_port(#[case] trading_mode: TradingMode, #[case] expected: u16) {
610        let gateway = DockerizedIBGateway::new(
611            DockerizedIBGatewayConfig::builder()
612                .username(SecretString::from("test-user"))
613                .password(SecretString::from("test-password"))
614                .trading_mode(trading_mode)
615                .build(),
616        )
617        .unwrap();
618
619        assert_eq!(gateway.port(), expected);
620        assert_eq!(gateway.username.expose_secret(), "test-user");
621        assert_eq!(gateway.password.expose_secret(), "test-password");
622        assert!(gateway.config.username.is_none());
623        assert!(gateway.config.password.is_none());
624    }
625
626    #[rstest]
627    #[case("Forking ::: Starting IBC Gateway", false)]
628    #[case("Started IB Gateway", false)]
629    #[case("Login has completed", true)]
630    #[case("Configuration tasks completed", true)]
631    #[case("Logged in to backend", true)]
632    #[case("Login successful", true)]
633    fn ready_log_markers_are_strict(#[case] logs: &str, #[case] expected: bool) {
634        assert_eq!(DockerizedIBGateway::logs_indicate_ready(logs), expected);
635    }
636
637    #[rstest]
638    #[case(
639        "2026-08-16T09:59:59Z Login has completed\n2026-08-16T10:00:01Z Started IB Gateway",
640        false
641    )]
642    #[case(
643        "2026-08-16T09:59:59Z Login has completed\n2026-08-16T10:00:01Z Login successful",
644        true
645    )]
646    #[case("2026-08-16T10:00:00Z Login has completed", true)]
647    fn readiness_uses_only_current_session_logs(#[case] logs: &str, #[case] expected: bool) {
648        let started_at = "2026-08-16T10:00:00Z".parse::<Timestamp>().unwrap();
649
650        assert_eq!(
651            DockerizedIBGateway::session_logs_indicate_ready(logs, started_at),
652            expected,
653        );
654    }
655}