use crate::{DEFAULT_SYMBOL, state};
use clap::Args as ClapArgs;
use ibapi::{
Client,
accounts::{AccountSummaryResult, AccountSummaryTags, PositionUpdate, types::AccountGroup},
contracts::{Contract, ContractDetails},
market_data::IgnoreSize,
orders::{Action, OrderData, OrderStatus, OrderUpdate, Orders},
prelude::{StreamExt, Subscription, SubscriptionItemStreamExt},
};
use log::{debug, error, info, warn};
use std::{
collections::{HashMap, HashSet},
error::Error,
io,
};
use time::{Duration, OffsetDateTime, Time};
use time_tz::{OffsetDateTimeExt, timezones::db::america::NEW_YORK};
use tokio::sync::RwLock;
use uuid::Uuid;
const RUN_DELAY: tokio::time::Duration = tokio::time::Duration::from_secs(1);
const RETRY_DELAY: tokio::time::Duration = tokio::time::Duration::from_secs(10);
const CONTRACT_DETAILS_TIMEOUT: tokio::time::Duration = tokio::time::Duration::from_secs(30);
const DEFAULT_BUYING_POWER_BUFFER: f64 = 20.0_f64;
const DEFAULT_INITIAL_MARGIN_REQUIREMENT: f64 = 75.0_f64;
const BUY_DISCOUNT_PERCENT: f64 = 1.0_f64;
const SELL_MARKUP_PERCENT: f64 = 0.5_f64;
const BUY_ORDER_TTL: Duration = Duration::seconds(5);
const SELL_ORDER_TTL: Duration = Duration::seconds(120);
const LIQUIDATION_SELL_ORDER_TTL: Duration = Duration::minutes(1);
const QUOTE_MAX_AGE: Duration = Duration::minutes(5);
const CANCEL_RETRY_DELAY: Duration = Duration::seconds(10);
const ORDER_REF_PREFIX: &str = "stockholm:";
const SMART_EXCHANGE: &str = "SMART";
pub const LIQUIDATION_START_TIME: Time = match Time::from_hms(15, 45, 0) {
Ok(time) => time,
Err(_) => panic!("The liquidation start time must be valid."),
};
pub const LIQUIDATION_END_TIME: Time = match Time::from_hms(20, 5, 0) {
Ok(time) => time,
Err(_) => panic!("The liquidation end time must be valid."),
};
#[derive(ClapArgs)]
pub struct Args {
#[arg(long, default_value = DEFAULT_SYMBOL)]
symbol: String,
#[arg(
long,
default_value_t = DEFAULT_BUYING_POWER_BUFFER,
value_parser = parse_percent
)]
buying_power_buffer: f64,
#[arg(
long,
default_value_t = DEFAULT_INITIAL_MARGIN_REQUIREMENT,
value_parser = parse_positive_percent
)]
initial_margin_requirement: f64,
}
struct VolatileState {
open_orders: HashMap<i32, VolatileOrder>,
position_shares: Option<f64>,
equity_with_loan_value: Option<f64>,
init_margin_req: Option<f64>,
bid_price: Option<f64>,
bid_price_timestamp: Option<OffsetDateTime>,
ask_price: Option<f64>,
ask_price_timestamp: Option<OffsetDateTime>,
}
struct RuntimeState {
persistent: state::State,
volatile: VolatileState,
}
struct VolatileOrder {
order_ref: String,
contract: Contract,
price: f64,
side: Side,
filled_shares: f64,
remaining_shares: f64,
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum Side {
Buy,
Sell,
}
impl Default for Args {
fn default() -> Self {
Self {
symbol: DEFAULT_SYMBOL.to_string(),
buying_power_buffer: DEFAULT_BUYING_POWER_BUFFER,
initial_margin_requirement: DEFAULT_INITIAL_MARGIN_REQUIREMENT,
}
}
}
fn initial_volatile_state() -> VolatileState {
VolatileState {
open_orders: HashMap::new(),
position_shares: None,
equity_with_loan_value: None,
init_margin_req: None,
bid_price: None,
bid_price_timestamp: None,
ask_price: None,
ask_price_timestamp: None,
}
}
pub async fn run(address: &str, client_id: i32, args: &Args) -> Result<(), Box<dyn Error>> {
let mut contract = Contract::stock(&args.symbol)
.on_exchange(SMART_EXCHANGE)
.build();
let runtime_state = RwLock::new(RuntimeState {
persistent: state::load().unwrap_or_else(|error| {
warn!(
"Unable to load state from disk. Proceeding with initial state. Details: {error}",
);
state::initial()
}),
volatile: initial_volatile_state(),
});
loop {
match Client::connect(address, client_id).await {
Ok(client) => {
if let Err(error) =
run_with_connection(&client, &mut contract, args, &runtime_state).await
{
error!("{error}");
}
}
Err(error) => error!("Connection to Interactive Brokers Gateway failed: {error}"),
}
tokio::time::sleep(RETRY_DELAY).await;
}
}
async fn run_with_connection(
client: &Client,
contract: &mut Contract,
args: &Args,
runtime_state: &RwLock<RuntimeState>,
) -> Result<(), Box<dyn Error>> {
if contract.contract_id == 0_i32 {
let matches = client
.contract_details_stream(contract)
.subscribe()
.await?
.collect_to_end_within(CONTRACT_DETAILS_TIMEOUT)
.await?;
contract.contract_id = resolve_contract_id(contract, &matches)?;
info!(
"Resolved {} to IBKR contract ID {}.",
contract.symbol,
contract.contract_id,
);
}
runtime_state.write().await.volatile = initial_volatile_state();
let order_updates = client.order_update_stream().await?;
fetch_orders(client, runtime_state).await?;
tokio::try_join!(
control_loop(
client,
runtime_state,
contract,
args.buying_power_buffer,
args.initial_margin_requirement,
),
stream_account_summary(client, runtime_state),
stream_order_updates(order_updates, runtime_state),
stream_positions(client, contract, runtime_state),
stream_tick_by_tick(client, contract, runtime_state),
clear_stale_quotes(runtime_state),
)?;
Ok(())
}
fn resolve_contract_id(contract: &Contract, matches: &[ContractDetails]) -> io::Result<i32> {
let Some(first_match) = matches.first() else {
return Err(io::Error::other(format!(
"IBKR returned no contract for {} on {}.",
contract.symbol,
contract.exchange,
)));
};
let contract_id = first_match.contract.contract_id;
if contract_id <= 0_i32
|| matches
.iter()
.any(|details| details.contract.contract_id != contract_id)
{
return Err(io::Error::other(format!(
"IBKR returned invalid or ambiguous contract IDs for {} on {}.",
contract.symbol,
contract.exchange,
)));
}
Ok(contract_id)
}
async fn control_loop(
client: &Client,
runtime_state: &RwLock<RuntimeState>,
contract: &Contract,
buying_power_buffer: f64,
initial_margin_requirement: f64,
) -> Result<(), Box<dyn Error>> {
loop {
run_control_step(
client,
runtime_state,
contract,
buying_power_buffer,
initial_margin_requirement,
)
.await?;
tokio::time::sleep(RUN_DELAY).await;
}
}
async fn stream_account_summary(
client: &Client,
runtime_state: &RwLock<RuntimeState>,
) -> Result<(), Box<dyn Error>> {
debug!("Requesting account summary…");
let subscription = client
.account_summary(&AccountGroup("All".to_string()), AccountSummaryTags::ALL)
.await?;
let mut summaries = subscription.filter_data();
while let Some(update) = summaries.next().await {
match update? {
AccountSummaryResult::Summary(summary) => {
update_account_metric(runtime_state, &summary.tag, &summary.value).await?;
if summary.currency.is_empty() {
debug!(
"Account summary for {}: {} = {}",
summary.account,
summary.tag,
summary.value,
);
} else {
debug!(
"Account summary for {}: {} = {} {}",
summary.account,
summary.tag,
summary.value,
summary.currency,
);
}
}
AccountSummaryResult::End => {
debug!("Finished listing initial account summary.");
}
}
}
Err(ibapi::Error::UnexpectedEndOfStream.into())
}
async fn stream_order_updates(
subscription: Subscription<OrderUpdate>,
runtime_state: &RwLock<RuntimeState>,
) -> Result<(), Box<dyn Error>> {
let mut updates = subscription.filter_data();
debug!("Streaming order updates…");
while let Some(update) = updates.next().await {
let update: OrderUpdate = update?;
match &update {
OrderUpdate::OpenOrder(data) if data.order.order_ref.starts_with(ORDER_REF_PREFIX) => {
update_open_order(runtime_state, data).await?;
}
OrderUpdate::OrderStatus(status) => {
update_order_status(runtime_state, status).await?;
}
OrderUpdate::OpenOrder(_)
| OrderUpdate::OrderBound(_)
| OrderUpdate::ExecutionData(_)
| OrderUpdate::CommissionReport(_) => {}
}
debug!("Order update: {update:?}");
}
Err(ibapi::Error::UnexpectedEndOfStream.into())
}
async fn stream_positions(
client: &Client,
contract: &Contract,
runtime_state: &RwLock<RuntimeState>,
) -> Result<(), Box<dyn Error>> {
let subscription = client.positions().await?;
let mut updates = subscription.filter_data();
debug!("Streaming positions for {}…", contract.symbol);
while let Some(update) = updates.next().await {
let mut state = runtime_state.write().await;
match update? {
PositionUpdate::Position(position)
if position.contract.contract_id == contract.contract_id =>
{
state.volatile.position_shares = Some(position.position);
}
PositionUpdate::Position(_) => {}
PositionUpdate::PositionEnd => {
state.volatile.position_shares.get_or_insert(0.0_f64);
}
}
}
Err(ibapi::Error::UnexpectedEndOfStream.into())
}
async fn clear_stale_quotes(runtime_state: &RwLock<RuntimeState>) -> Result<(), Box<dyn Error>> {
loop {
tokio::time::sleep(RUN_DELAY).await;
let mut state = runtime_state.write().await;
clear_stale_quote_prices(&mut state.volatile);
}
}
async fn stream_tick_by_tick(
client: &Client,
contract: &Contract,
runtime_state: &RwLock<RuntimeState>,
) -> Result<(), Box<dyn Error>> {
let exchange = &contract.exchange;
let subscription = client
.tick_by_tick(contract, 0)
.bid_ask(IgnoreSize::Yes)
.await?;
let mut quotes = subscription.filter_data();
debug!(
"Streaming tick-by-tick quotes for {} from {exchange}…",
contract.symbol,
);
while let Some(quote) = quotes.next().await {
let quote = quote?;
{
let mut state = runtime_state.write().await;
state.volatile.bid_price = (quote.bid_price > 0.0_f64).then_some(quote.bid_price);
state.volatile.bid_price_timestamp = state.volatile.bid_price.map(|_| quote.time);
state.volatile.ask_price = (quote.ask_price > 0.0_f64).then_some(quote.ask_price);
state.volatile.ask_price_timestamp = state.volatile.ask_price.map(|_| quote.time);
}
debug!(
"Tick-by-tick quote for {} ({exchange}): {quote:?}",
contract.symbol,
);
}
Err(ibapi::Error::UnexpectedEndOfStream.into())
}
async fn run_control_step(
client: &Client,
runtime_state: &RwLock<RuntimeState>,
contract: &Contract,
buying_power_buffer: f64,
initial_margin_requirement: f64,
) -> Result<(), Box<dyn Error>> {
let liquidating = is_liquidating();
cancel_expired_orders(client, runtime_state, contract, liquidating).await?;
let (buying_power, bid_price, ask_price, sellable_shares) = {
let state = runtime_state.read().await;
let state = &state.volatile;
let open_buy_order_value = calculate_open_buy_order_value(&state.open_orders);
let buying_power =
state
.equity_with_loan_value
.zip(state.init_margin_req)
.map(|(equity, margin)| {
calculate_buying_power(
equity,
margin,
buying_power_buffer,
initial_margin_requirement,
open_buy_order_value,
)
});
let reserved_sell_shares = calculate_open_sell_shares(&state.open_orders, contract);
let sellable_shares = state
.position_shares
.map(|shares| (shares - reserved_sell_shares).max(0.0_f64).floor());
let open_orders = format_open_orders(&state.open_orders);
info!(
concat!(
"Equity: {}; buying power: {}; open orders: {}; ",
"bid: {}; ask: {}; liquidating: {}",
),
state
.equity_with_loan_value
.map_or_else(|| "unavailable".to_string(), |equity| equity.to_string()),
buying_power.map_or_else(|| "unavailable".to_string(), |power| power.to_string()),
open_orders,
state
.bid_price
.map_or_else(|| "unavailable".to_string(), |price| price.to_string()),
state
.ask_price
.map_or_else(|| "unavailable".to_string(), |price| price.to_string()),
liquidating,
);
(
buying_power,
state.bid_price,
state.ask_price,
sellable_shares,
)
};
let (buy_limit, sell_limit) = calculate_order_limits(bid_price, ask_price, liquidating);
if let (Some(buying_power), Some(limit)) = (buying_power, buy_limit)
&& limit > 0.0_f64
{
let shares = (buying_power / limit).floor();
if shares >= 1.0_f64 {
place_limit_buy(client, contract, shares, limit, runtime_state).await?;
}
}
if let (Some(limit), Some(sellable_shares)) = (sell_limit, sellable_shares)
&& limit > 0.0_f64
&& sellable_shares > 0.0_f64
{
place_limit_sell(client, contract, sellable_shares, limit, runtime_state).await?;
}
Ok(())
}
fn format_open_orders(open_orders: &HashMap<i32, VolatileOrder>) -> String {
let mut open_orders = open_orders.iter().collect::<Vec<_>>();
open_orders.sort_unstable_by_key(|(order_id, _)| *order_id);
let open_orders = open_orders
.into_iter()
.map(|(_, order)| {
let side = match order.side {
Side::Buy => "buy",
Side::Sell => "sell",
};
format!(
"{side} {} @ ${:.2} ({} filled, {} remaining)",
order.contract.symbol,
order.price,
order.filled_shares,
order.remaining_shares,
)
})
.collect::<Vec<_>>()
.join(", ");
format!("[{open_orders}]")
}
async fn cancel_expired_orders(
client: &Client,
runtime_state: &RwLock<RuntimeState>,
contract: &Contract,
liquidating: bool,
) -> Result<(), Box<dyn Error>> {
let cancellation_attempts = {
let mut state = runtime_state.write().await;
let volatile_orders = state
.volatile
.open_orders
.iter()
.map(|(&order_id, order)| {
(
order.order_ref.clone(),
(order_id, order.side, order.contract.contract_id),
)
})
.collect::<HashMap<_, _>>();
let mut attempts = Vec::new();
for order in &mut state.persistent.open_orders {
let Some((order_id, side, contract_id)) = volatile_orders.get(&order.order_ref) else {
continue;
};
let liquidation_order = liquidating && *contract_id == contract.contract_id;
if cancellation_due(order, *side, liquidation_order) {
order.last_cancelled_at = Some(OffsetDateTime::now_utc());
attempts.push((*order_id, order.order_ref.clone()));
}
}
if !attempts.is_empty() {
state::save(&state.persistent)?;
}
attempts
};
for (order_id, order_ref) in cancellation_attempts {
info!("Cancelling expired order {order_id} ({order_ref})…");
let _subscription = client.cancel_order(order_id, "").await?;
}
Ok(())
}
fn is_liquidating() -> bool {
let eastern_time = OffsetDateTime::now_utc().to_timezone(NEW_YORK).time();
eastern_time >= LIQUIDATION_START_TIME && eastern_time < LIQUIDATION_END_TIME
}
async fn place_limit_buy(
client: &Client,
contract: &Contract,
shares: f64,
limit: f64,
runtime_state: &RwLock<RuntimeState>,
) -> Result<(), Box<dyn Error>> {
let order_ref = format!("{ORDER_REF_PREFIX}{}", Uuid::new_v4().simple());
let mut order = client
.order(contract)
.buy(shares)
.limit(limit)
.outside_rth()
.build()?;
order.order_ref.clone_from(&order_ref);
order.include_overnight = true;
let order_id = client.next_order_id();
{
let mut state = runtime_state.write().await;
state.persistent.open_orders.push(state::OpenOrder {
order_ref: order_ref.clone(),
perm_id: None,
created_at: OffsetDateTime::now_utc(),
last_cancelled_at: None,
});
state.volatile.open_orders.insert(
order_id,
VolatileOrder {
order_ref: order_ref.clone(),
contract: contract.clone(),
price: limit,
side: Side::Buy,
filled_shares: 0.0_f64,
remaining_shares: shares,
},
);
state::save(&state.persistent)?;
}
client.submit_order(order_id, contract, &order).await?;
info!(
"Submitted limit buy {order_id} ({order_ref}): {shares} {} @ ${limit:.2}",
contract.symbol,
);
Ok(())
}
async fn place_limit_sell(
client: &Client,
contract: &Contract,
shares: f64,
limit: f64,
runtime_state: &RwLock<RuntimeState>,
) -> Result<(), Box<dyn Error>> {
let order_ref = format!("{ORDER_REF_PREFIX}{}", Uuid::new_v4().simple());
let mut order = client
.order(contract)
.sell(shares)
.limit(limit)
.outside_rth()
.build()?;
order.order_ref.clone_from(&order_ref);
order.include_overnight = true;
let order_id = client.next_order_id();
{
let mut state = runtime_state.write().await;
state.persistent.open_orders.push(state::OpenOrder {
order_ref: order_ref.clone(),
perm_id: None,
created_at: OffsetDateTime::now_utc(),
last_cancelled_at: None,
});
state.volatile.open_orders.insert(
order_id,
VolatileOrder {
order_ref: order_ref.clone(),
contract: contract.clone(),
price: limit,
side: Side::Sell,
filled_shares: 0.0_f64,
remaining_shares: shares,
},
);
state::save(&state.persistent)?;
}
client.submit_order(order_id, contract, &order).await?;
info!(
"Submitted limit sell {order_id} ({order_ref}): {shares} {} @ ${limit:.2}",
contract.symbol,
);
Ok(())
}
async fn fetch_orders(
client: &Client,
runtime_state: &RwLock<RuntimeState>,
) -> Result<(), Box<dyn Error>> {
debug!("Requesting Stockholm open orders…");
let subscription = client.all_open_orders().await?;
let mut orders = subscription.filter_data();
let mut order_count: usize = 0;
let mut open_order_refs = HashSet::new();
while let Some(order) = orders.next().await {
match order? {
Orders::OrderData(data) if data.order.order_ref.starts_with(ORDER_REF_PREFIX) => {
order_count += 1;
open_order_refs.insert(data.order.order_ref.clone());
update_open_order(runtime_state, &data).await?;
debug!("Stockholm open order: {data:?}");
}
Orders::OrderStatus(status) => {
update_order_status(runtime_state, &status).await?;
}
Orders::OrderData(_) => {}
}
}
{
let mut state = runtime_state.write().await;
let previous_len = state.persistent.open_orders.len();
state
.persistent
.open_orders
.retain(|order| open_order_refs.contains(&order.order_ref));
state
.volatile
.open_orders
.retain(|_, order| open_order_refs.contains(&order.order_ref));
if state.persistent.open_orders.len() != previous_len {
state::save(&state.persistent)?;
}
}
if order_count == 0 {
debug!("No Stockholm open orders found.");
} else if order_count == 1 {
debug!("Finished listing 1 Stockholm open order.");
} else {
debug!("Finished listing {order_count} Stockholm open orders.");
}
Ok(())
}
async fn update_account_metric(
runtime_state: &RwLock<RuntimeState>,
tag: &str,
value: &str,
) -> io::Result<()> {
let Ok(value) = value.parse::<f64>() else {
return Ok(());
};
if !value.is_finite() {
return Ok(());
}
let mut state = runtime_state.write().await;
match tag {
AccountSummaryTags::EQUITY_WITH_LOAN_VALUE => {
state.volatile.equity_with_loan_value = Some(value);
}
AccountSummaryTags::INIT_MARGIN_REQ => state.volatile.init_margin_req = Some(value),
_ => {}
}
Ok(())
}
async fn update_open_order(
runtime_state: &RwLock<RuntimeState>,
data: &OrderData,
) -> io::Result<()> {
if data.contract.contract_id <= 0_i32 {
return Err(io::Error::other(format!(
"IBKR returned no valid contract ID for Stockholm order {}.",
data.order.order_ref,
)));
}
let volatile_order = VolatileOrder {
order_ref: data.order.order_ref.clone(),
contract: data.contract.clone(),
price: data
.order
.limit_price
.ok_or_else(|| io::Error::other("A Stockholm order is missing its limit price."))?,
side: match data.order.action {
Action::Buy => Side::Buy,
Action::Sell => Side::Sell,
Action::SellShort | Action::SellLong => {
return Err(io::Error::other(
"A Stockholm order has an unsupported institutional side.",
));
}
},
filled_shares: data.order.filled_quantity,
remaining_shares: data.order.total_quantity - data.order.filled_quantity,
};
let perm_id = (data.order.perm_id != 0).then_some(data.order.perm_id);
let mut state = runtime_state.write().await;
state
.volatile
.open_orders
.insert(data.order_id, volatile_order);
let changed = if let Some(order) = state
.persistent
.open_orders
.iter_mut()
.find(|order| order.order_ref == data.order.order_ref)
{
let changed = order.perm_id != perm_id;
order.perm_id = perm_id;
changed
} else {
state.persistent.open_orders.push(state::OpenOrder {
order_ref: data.order.order_ref.clone(),
perm_id,
created_at: OffsetDateTime::now_utc(),
last_cancelled_at: None,
});
true
};
if changed {
state::save(&state.persistent)?;
}
Ok(())
}
async fn update_order_status(
runtime_state: &RwLock<RuntimeState>,
status: &OrderStatus,
) -> io::Result<()> {
let mut state = runtime_state.write().await;
let persistent_changed = if status.status.is_terminal() {
let order_ref = state
.volatile
.open_orders
.remove(&status.order_id)
.map(|order| order.order_ref);
let previous_len = state.persistent.open_orders.len();
if let Some(order_ref) = order_ref {
state
.persistent
.open_orders
.retain(|order| order.order_ref != order_ref);
} else if status.perm_id != 0 {
state
.persistent
.open_orders
.retain(|order| order.perm_id != Some(status.perm_id));
}
state.persistent.open_orders.len() != previous_len
} else {
if let Some(order) = state.volatile.open_orders.get_mut(&status.order_id) {
order.filled_shares = status.filled;
order.remaining_shares = status.remaining;
}
false
};
if persistent_changed {
state::save(&state.persistent)?;
}
Ok(())
}
fn parse_positive_percent(value: &str) -> Result<f64, String> {
match value.parse::<f64>() {
Ok(value) if value > 0.0_f64 && value <= 100.0_f64 => Ok(value),
_ => Err("The percentage must be a finite number in the range (0, 100].".to_string()),
}
}
fn parse_percent(value: &str) -> Result<f64, String> {
match value.parse::<f64>() {
Ok(value) if (0.0_f64..=100.0_f64).contains(&value) => Ok(value),
_ => Err("The percentage must be a finite number in the range [0, 100].".to_string()),
}
}
fn calculate_open_buy_order_value(open_orders: &HashMap<i32, VolatileOrder>) -> f64 {
open_orders
.values()
.filter(|order| order.side == Side::Buy)
.map(|order| order.price * order.remaining_shares)
.sum()
}
fn calculate_open_sell_shares(
open_orders: &HashMap<i32, VolatileOrder>,
contract: &Contract,
) -> f64 {
open_orders
.values()
.filter(|order| {
order.contract.contract_id == contract.contract_id && order.side == Side::Sell
})
.map(|order| order.remaining_shares)
.sum()
}
fn calculate_order_limits(
bid_price: Option<f64>,
ask_price: Option<f64>,
liquidating: bool,
) -> (Option<f64>, Option<f64>) {
if liquidating {
(None, ask_price.map(round_up_to_cent))
} else {
(
bid_price.map(|price| {
round_down_to_cent(price * (1.0_f64 - BUY_DISCOUNT_PERCENT / 100.0_f64))
}),
ask_price
.map(|price| round_up_to_cent(price * (1.0_f64 + SELL_MARKUP_PERCENT / 100.0_f64))),
)
}
}
fn clear_stale_quote_prices(state: &mut VolatileState) {
let cutoff = OffsetDateTime::now_utc() - QUOTE_MAX_AGE;
if state
.bid_price_timestamp
.is_some_and(|timestamp| timestamp < cutoff)
{
state.bid_price = None;
state.bid_price_timestamp = None;
}
if state
.ask_price_timestamp
.is_some_and(|timestamp| timestamp < cutoff)
{
state.ask_price = None;
state.ask_price_timestamp = None;
}
}
fn cancellation_due(order: &state::OpenOrder, side: Side, liquidating: bool) -> bool {
let time_to_live = if liquidating {
match side {
Side::Buy => Duration::ZERO,
Side::Sell => LIQUIDATION_SELL_ORDER_TTL,
}
} else {
match side {
Side::Buy => BUY_ORDER_TTL,
Side::Sell => SELL_ORDER_TTL,
}
};
OffsetDateTime::now_utc() >= order.created_at + time_to_live
&& order.last_cancelled_at.is_none_or(|last_cancelled_at| {
OffsetDateTime::now_utc() >= last_cancelled_at + CANCEL_RETRY_DELAY
})
}
fn calculate_buying_power(
equity_with_loan_value: f64,
init_margin_req: f64,
buying_power_buffer: f64,
initial_margin_requirement: f64,
open_buy_order_value: f64,
) -> f64 {
let margin_ratio = initial_margin_requirement / 100.0_f64;
let effective_equity = equity_with_loan_value * (1.0_f64 - buying_power_buffer / 100.0_f64);
let open_buy_order_margin = open_buy_order_value * margin_ratio;
let margin_capacity = (effective_equity - init_margin_req - open_buy_order_margin).max(0.0_f64);
round_down_to_cent(margin_capacity / margin_ratio)
}
fn round_down_to_cent(price: f64) -> f64 {
(price * 100.0_f64).floor() / 100.0_f64
}
fn round_up_to_cent(price: f64) -> f64 {
(price * 100.0_f64).ceil() / 100.0_f64
}
#[cfg(test)]
mod tests {
use super::{
Args, RuntimeState, Side, VolatileOrder, calculate_buying_power,
calculate_open_buy_order_value, calculate_open_sell_shares, calculate_order_limits,
initial_volatile_state, resolve_contract_id, round_down_to_cent, round_up_to_cent,
update_account_metric,
};
use crate::state;
use clap::Parser;
use ibapi::{
accounts::AccountSummaryTags,
contracts::{Contract, ContractDetails},
};
use std::collections::HashMap;
use tokio::sync::RwLock;
#[derive(Parser)]
struct TestCli {
#[command(flatten)]
args: Args,
}
#[test]
fn default_symbol() {
let cli = TestCli::try_parse_from(["run"]).unwrap();
assert_eq!(cli.args.symbol, "SOXL");
assert!((cli.args.buying_power_buffer - 20.0_f64).abs() < f64::EPSILON);
assert!((cli.args.initial_margin_requirement - 75.0_f64).abs() < f64::EPSILON);
}
#[test]
fn explicit_symbol() {
let cli = TestCli::try_parse_from(["run", "--symbol", "AAPL"]).unwrap();
assert_eq!(cli.args.symbol, "AAPL");
}
#[test]
fn validate_initial_margin_requirement() {
let valid = TestCli::try_parse_from(["run", "--initial-margin-requirement", "100"]);
let zero = TestCli::try_parse_from(["run", "--initial-margin-requirement", "0"]);
let excessive = TestCli::try_parse_from(["run", "--initial-margin-requirement", "100.1"]);
let nonfinite = TestCli::try_parse_from(["run", "--initial-margin-requirement", "NaN"]);
assert!((valid.unwrap().args.initial_margin_requirement - 100.0_f64).abs() < f64::EPSILON);
assert!(zero.is_err());
assert!(excessive.is_err());
assert!(nonfinite.is_err());
}
#[test]
fn validate_buying_power_buffer() {
let zero = TestCli::try_parse_from(["run", "--buying-power-buffer", "0"]);
let full = TestCli::try_parse_from(["run", "--buying-power-buffer", "100"]);
let excessive = TestCli::try_parse_from(["run", "--buying-power-buffer", "100.1"]);
let negative = TestCli::try_parse_from(["run", "--buying-power-buffer", "-1"]);
let nonfinite = TestCli::try_parse_from(["run", "--buying-power-buffer", "NaN"]);
assert!(zero.is_ok());
assert!(full.is_ok());
assert!(excessive.is_err());
assert!(negative.is_err());
assert!(nonfinite.is_err());
}
#[test]
fn buffer_and_round_down_buying_power() {
let buying_power = calculate_buying_power(1_000.0, 100.0, 20.0, 75.0, 0.0);
assert!((buying_power - 933.33_f64).abs() < f64::EPSILON);
}
#[test]
fn clamp_negative_buying_power() {
let buying_power = calculate_buying_power(1_000.0, 900.0, 20.0, 75.0, 0.0);
assert!(buying_power.abs() < f64::EPSILON);
}
#[test]
fn reserve_open_buy_order_margin() {
let buying_power = calculate_buying_power(1_000.0, 100.0, 20.0, 75.0, 200.0);
assert!((buying_power - 733.33_f64).abs() < f64::EPSILON);
}
#[test]
fn resolve_only_unambiguous_contract_ids() {
let stock = Contract::stock("SOXL").build();
let details = |contract_id, exchange| ContractDetails {
contract: Contract {
contract_id,
exchange,
..stock.clone()
},
..ContractDetails::default()
};
let smart = details(101_i32, "SMART".into());
let arca = details(101_i32, "ARCA".into());
assert_eq!(
resolve_contract_id(&stock, &[smart.clone(), arca]).unwrap(),
101_i32,
);
assert!(resolve_contract_id(&stock, &[]).is_err());
assert!(resolve_contract_id(&stock, &[details(0_i32, "SMART".into())]).is_err());
assert!(resolve_contract_id(&stock, &[smart, details(102_i32, "SMART".into())]).is_err());
}
#[test]
fn total_outstanding_order_reservations() {
let mut soxl = Contract::stock("SOXL").build();
soxl.contract_id = 101_i32;
let soxl_on_arca = Contract {
exchange: "ARCA".into(),
..soxl.clone()
};
let open_orders = HashMap::from([
(
1_i32,
VolatileOrder {
order_ref: "stockholm:buy".to_string(),
contract: soxl.clone(),
price: 10.0,
side: Side::Buy,
filled_shares: 3.0,
remaining_shares: 2.0,
},
),
(
2_i32,
VolatileOrder {
order_ref: "stockholm:sell".to_string(),
contract: soxl_on_arca,
price: 20.0,
side: Side::Sell,
filled_shares: 0.0,
remaining_shares: 4.0,
},
),
]);
let other_contract = Contract {
contract_id: 102_i32,
..soxl.clone()
};
assert!((calculate_open_buy_order_value(&open_orders) - 20.0_f64).abs() < f64::EPSILON);
assert!((calculate_open_sell_shares(&open_orders, &soxl) - 4.0_f64).abs() < f64::EPSILON);
assert!(calculate_open_sell_shares(&open_orders, &other_contract).abs() < f64::EPSILON);
}
#[test]
fn select_limits_for_current_trading_behavior() {
assert_eq!(
calculate_order_limits(Some(10.129_f64), Some(10.231_f64), false),
(Some(10.02_f64), Some(10.29_f64)),
);
assert_eq!(
calculate_order_limits(Some(10.129_f64), Some(10.231_f64), true),
(None, Some(10.24_f64)),
);
assert_eq!(
calculate_order_limits(Some(10.129_f64), None, true),
(None, None),
);
}
#[test]
fn round_limit_prices_conservatively() {
assert!((round_down_to_cent(10.129_f64) - 10.12_f64).abs() < f64::EPSILON);
assert!((round_up_to_cent(10.121_f64) - 10.13_f64).abs() < f64::EPSILON);
}
#[tokio::test]
async fn retain_only_valid_account_metrics() {
let state = RwLock::new(RuntimeState {
persistent: state::initial(),
volatile: initial_volatile_state(),
});
update_account_metric(&state, AccountSummaryTags::EQUITY_WITH_LOAN_VALUE, "1234.5")
.await
.unwrap();
update_account_metric(&state, AccountSummaryTags::INIT_MARGIN_REQ, "234.5")
.await
.unwrap();
update_account_metric(&state, AccountSummaryTags::INIT_MARGIN_REQ, "NaN")
.await
.unwrap();
update_account_metric(&state, AccountSummaryTags::NET_LIQUIDATION, "9999")
.await
.unwrap();
let state = state.read().await;
assert_eq!(state.volatile.equity_with_loan_value, Some(1234.5_f64));
assert_eq!(state.volatile.init_margin_req, Some(234.5_f64));
}
}