//! Basic TWS Connection Example //! //! This example demonstrates how to establish a basic connection to //! Interactive Brokers TWS or Gateway. //! //! Usage: //! cargo run --example basic_connection //! //! Prerequisites: //! - TWS or IB Gateway running on localhost //! - API connections enabled in TWS settings //! - Socket port configured (default: 7497 for paper trading) use data::{init, paper_trading_config, validate_config, InteractiveBrokersAdapter}; use std::time::Duration; use tokio::time::sleep; use tracing::{error, info}; #[tokio::main] async fn main() -> Result<(), Box> { // Initialize logging init()?; info!("=== Interactive Brokers Basic Connection Example ==="); // Get paper trading configuration let config = paper_trading_config(); // Validate configuration if let Err(e) = validate_config(&config) { error!("Invalid configuration: {}", e); return Err(e.into()); } info!("Configuration:"); info!(" Host: {}", config.host); info!(" Port: {}", config.port); info!(" Client ID: {}", config.client_id); info!(" Account ID: {}", config.account_id); // Create adapter let mut adapter = InteractiveBrokersAdapter::new(config); // Attempt connection info!("Connecting to TWS..."); match adapter.connect().await { Ok(()) => { info!("✅ Successfully connected to TWS!"); // Check connection state let state = adapter.get_connection_state().await; info!("Connection state: {:?}", state); // Keep connection alive for a few seconds info!("Maintaining connection for 10 seconds..."); sleep(Duration::from_secs(10)).await; // Disconnect cleanly info!("Disconnecting from TWS..."); adapter.disconnect().await?; info!("✅ Successfully disconnected from TWS"); } Err(e) => { error!("❌ Failed to connect to TWS: {}", e); error!("Please ensure:"); error!(" 1. TWS or IB Gateway is running"); error!(" 2. API connections are enabled in settings"); error!(" 3. Socket port is configured correctly"); error!(" 4. Client ID is not already in use"); return Err(e); } } info!("=== Example completed successfully ==="); Ok(()) }