Files
eventbook-exchange/crates/exchange/src/minimum_size.rs
T

80 lines
2.6 KiB
Rust

use anyhow::{ensure, Result};
use rusqlite::{params, Connection, OptionalExtension, Transaction};
const SCALE: i64 = 1_000_000;
pub(crate) struct MinimumSize(i64);
impl MinimumSize {
pub fn configure(tx: &Transaction, market: &str, input: &str) -> Result<()> {
let (whole, fraction) = input.split_once('.').unwrap_or((input, ""));
ensure!(
!whole.is_empty()
&& whole.bytes().all(|b| b.is_ascii_digit())
&& fraction.bytes().all(|b| b.is_ascii_digit())
&& fraction.len() <= 6
&& !input.ends_with('.'),
"min_order_size must be positive decimal shares with at most six decimals"
);
let whole: i64 = whole.parse()?;
ensure!(
whole <= 1_000_000_000,
"min_order_size exceeds supported order size"
);
let fraction = if fraction.is_empty() {
0
} else {
fraction.parse::<i64>()? * 10_i64.pow(6 - fraction.len() as u32)
};
let micros = whole * SCALE + fraction;
ensure!(
(1..=1_000_000_000 * SCALE).contains(&micros),
"min_order_size out of range"
);
tx.execute(
"INSERT INTO market_minimum_sizes(market,microshares) VALUES(?,?)",
params![market, micros],
)?;
Ok(())
}
pub fn load(db: &Connection, market: &str) -> Result<Option<Self>> {
Ok(db
.prepare_cached("SELECT microshares FROM market_minimum_sizes WHERE market=?")?
.query_row([market], |row| Ok(Self(row.get(0)?)))
.optional()?)
}
pub fn text(&self) -> String {
Self::format_microshares(self.0)
}
pub fn format_microshares(micros: i64) -> String {
let digits = format!("{}.{:06}", micros / SCALE, micros % SCALE);
digits
.trim_end_matches('0')
.trim_end_matches('.')
.to_owned()
}
pub fn check_microshares(&self, shares: i64) -> Result<()> {
ensure!(
shares >= self.0,
"order is below min_order_size of {} shares",
self.text()
);
Ok(())
}
pub fn check_budget(&self, cents: i64, max_price: i64, fee_rate: i64) -> Result<()> {
let lots = (self.0 + crate::lots::MICROS - 1) / crate::lots::MICROS;
let required = lots * max_price + crate::fees::lot_fee(fee_rate, max_price * 100, lots);
ensure!(
cents * 10000 >= required,
"cash budget at protection price is below min_order_size of {} shares",
self.text()
);
Ok(())
}
}