#![allow(clippy::uninlined_format_args)]
use futures::StreamExt;
use ibapi::contracts::Contract;
use ibapi::orders::OrderUpdate;
use ibapi::subscriptions::SubscriptionItemStreamExt;
use ibapi::Client;
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
env_logger::init();
let client = Client::connect("127.0.0.1:4002", 100).await?;
println!("Connected to server version {}", client.server_version());
let order_stream = client.order_update_stream().await?;
println!("Created order update stream");
let monitor_handle = tokio::spawn(async move {
println!("Starting order update monitor...");
let mut order_stream = order_stream.filter_data();
while let Some(update) = order_stream.next().await {
match update {
Ok(OrderUpdate::OrderStatus(status)) => {
println!("Order Status Update:");
println!(" Order ID: {}", status.order_id);
println!(" Status: {}", status.status);
println!(" Filled: {}", status.filled);
println!(" Remaining: {}", status.remaining);
match status.average_fill_price {
Some(price) => println!(" Avg Fill Price: {price}"),
None => println!(" Avg Fill Price: -"),
}
}
Ok(OrderUpdate::OpenOrder(order_data)) => {
println!("Open Order Update:");
println!(" Order ID: {}", order_data.order_id);
println!(" Symbol: {}", order_data.contract.symbol);
println!(" Action: {:?}", order_data.order.action);
println!(" Quantity: {}", order_data.order.total_quantity);
println!(" Order Type: {}", order_data.order.order_type);
println!(" Status: {}", order_data.order_state.status);
}
Ok(OrderUpdate::ExecutionData(exec_data)) => {
println!("Execution:");
println!(" Order ID: {}", exec_data.execution.order_id);
println!(" Symbol: {}", exec_data.contract.symbol);
println!(" Side: {}", exec_data.execution.side);
println!(" Shares: {}", exec_data.execution.shares);
println!(" Price: {}", exec_data.execution.price);
println!(" Time: {}", exec_data.execution.time);
}
Ok(OrderUpdate::CommissionReport(report)) => {
println!("Commission Report:");
println!(" Execution ID: {}", report.execution_id);
println!(" Commission: {} {}", report.commission, report.currency);
}
Err(e) => {
eprintln!("Error in order stream: {e:?}");
break;
}
}
println!("---");
}
println!("Order update monitor stopped");
});
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
let contract = Contract::stock("AAPL").build();
let order_id = client.order(&contract).buy(100).limit(150.0).submit().await?;
println!("\nSubmitted order: {order_id}");
println!("\nWaiting for order updates...");
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
let order_id2 = client.order(&contract).sell(50).limit(160.0).submit().await?;
println!("\nSubmitted order: {order_id2}");
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
monitor_handle.abort();
println!("\nExample complete");
Ok(())
}