Validate per-market minimum share size on order entry and previews

This commit is contained in:
2026-12-03 06:06:20 +08:00
parent 2306c6fd96
commit a7e31fa2ef
13 changed files with 222 additions and 4 deletions
+81
View File
@@ -0,0 +1,81 @@
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_shares(&self, qty: i64) -> Result<()> {
ensure!(
qty * SCALE >= 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<()> {
// Whole shares are the simulator's executable quantity unit. The
// submitted cash cap includes the taker fee at the protection price.
let qty = (self.0 + SCALE - 1) / SCALE;
let required = qty * max_price * 10000 + crate::fees::micros(fee_rate, max_price, qty);
ensure!(
cents * 10000 >= required,
"cash budget at protection price is below min_order_size of {} shares",
self.text()
);
Ok(())
}
}