Validate per-market minimum share size on order entry and previews
This commit is contained in:
@@ -34,6 +34,8 @@ pub(crate) fn market_assets(db: &Connection, market: &str) -> Result<Value> {
|
||||
Ok(detail)
|
||||
},
|
||||
)?;
|
||||
detail["min_order_size"] =
|
||||
json!(crate::minimum_size::MinimumSize::load(db, market)?.map(|size| size.text()));
|
||||
detail["taker_fee_rate_ppm"] = json!(crate::fees::rate(db, market)?);
|
||||
Ok(detail)
|
||||
}
|
||||
|
||||
@@ -71,6 +71,9 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
!post_only || (stage == "continuous" && matches!(tif, TimeInForce::Gtc | TimeInForce::Gtd)),
|
||||
"post-only requires continuous GTC or GTD"
|
||||
);
|
||||
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
|
||||
minimum.check_shares(qty)?;
|
||||
}
|
||||
let deadline = match tif {
|
||||
TimeInForce::Gtd => {
|
||||
let expiration =
|
||||
@@ -181,6 +184,10 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
|
||||
matches!(tif, TimeInForce::Fak | TimeInForce::Fok),
|
||||
"market buy requires FAK or FOK"
|
||||
);
|
||||
let rate = crate::fees::rate(tx, &market)?;
|
||||
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
|
||||
minimum.check_budget(amount_cents, max_price, rate)?;
|
||||
}
|
||||
ledger::cash(tx, &account, -amount_cents)?;
|
||||
tx.execute(
|
||||
"INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status)
|
||||
@@ -193,7 +200,6 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
|
||||
.get(&market, &outcome)
|
||||
.map(|b| b.match_budget_buy(seq, max_price, amount_cents))
|
||||
.unwrap_or_default();
|
||||
let rate = crate::fees::rate(tx, &market)?;
|
||||
crate::fees::fit_budget(rate, &mut fills, amount_cents);
|
||||
ensure!(!fills.is_empty(), "no affordable liquidity");
|
||||
let quantity: i64 = fills.iter().map(|f| f.quantity).sum();
|
||||
|
||||
@@ -322,8 +322,10 @@ impl Query {
|
||||
let levels = if side == "buy" { &mut bids } else { &mut asks };
|
||||
levels.push(json!({"price_micros":price*10000,"size":size}));
|
||||
}
|
||||
let minimum =
|
||||
crate::minimum_size::MinimumSize::load(db, &market)?.map(|size| size.text());
|
||||
Ok(
|
||||
json!({"asset_id":assets::id(&market,&outcome),"market":market,"outcome":outcome,"phase":phase,"bids":bids,"asks":asks}),
|
||||
json!({"asset_id":assets::id(&market,&outcome),"market":market,"outcome":outcome,"phase":phase,"bids":bids,"asks":asks,"min_order_size":minimum}),
|
||||
)
|
||||
}
|
||||
Self::Quote { market, outcome } => {
|
||||
@@ -386,10 +388,11 @@ impl Query {
|
||||
let mut stmt = db.prepare(
|
||||
"SELECT s.market,COALESCE(a.question,s.question),yes_label,no_label,terms,source,resolver,rules_version,
|
||||
m.rules,m.phase,COALESCE(a.name,group_title),group_order,n.group_id,n.ordinal,
|
||||
a.role,a.clarification,a.named_at
|
||||
a.role,a.clarification,a.named_at,minimum.microshares
|
||||
FROM listed_markets s JOIN markets m ON m.id=s.market
|
||||
LEFT JOIN neg_risk_members n ON n.market=s.market
|
||||
LEFT JOIN augmented_outcomes a ON a.market=s.market
|
||||
LEFT JOIN market_minimum_sizes minimum ON minimum.market=s.market
|
||||
WHERE event=? AND (a.role IS NULL OR a.role<>'placeholder') ORDER BY group_order,s.market"
|
||||
)?;
|
||||
let volume = crate::volume::Report::read(db, Some(&id), None)?;
|
||||
@@ -413,6 +416,7 @@ impl Query {
|
||||
"augmented_role":r.get::<_,Option<String>>(14)?,
|
||||
"clarification":r.get::<_,Option<String>>(15)?,
|
||||
"named_at":r.get::<_,Option<i64>>(16)?,
|
||||
"min_order_size":r.get::<_,Option<i64>>(17)?.map(crate::minimum_size::MinimumSize::format_microshares),
|
||||
"source":r.get::<_,String>(5)?,
|
||||
"resolver":r.get::<_,String>(6)?,
|
||||
"rules_version":r.get::<_,i64>(7)?,
|
||||
|
||||
@@ -12,6 +12,7 @@ pub(crate) enum Command {
|
||||
market: String,
|
||||
rules: String,
|
||||
taker_fee_rate_ppm: Option<i64>,
|
||||
min_order_size: Option<String>,
|
||||
#[serde(default)]
|
||||
listing: Option<crate::catalog::Listing>,
|
||||
resolution: Option<crate::resolution::Policy>,
|
||||
|
||||
@@ -73,6 +73,13 @@ impl Request {
|
||||
"invalid outcome or price"
|
||||
);
|
||||
phase(tx, &market, &["continuous"])?;
|
||||
let rate = crate::fees::rate(tx, &market)?;
|
||||
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
|
||||
match side {
|
||||
Side::Buy => minimum.check_budget(requested, limit, rate)?,
|
||||
Side::Sell => minimum.check_shares(requested)?,
|
||||
}
|
||||
}
|
||||
let changes = books.changes(tx)?;
|
||||
books.apply(changes);
|
||||
// The hypothetical incoming order follows all resting orders in time priority.
|
||||
@@ -88,7 +95,6 @@ impl Request {
|
||||
}),
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let rate = crate::fees::rate(tx, &market)?;
|
||||
if side == Side::Buy {
|
||||
crate::fees::fit_budget(rate, &mut fills, requested);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ mod cancellation;
|
||||
mod command;
|
||||
mod ledger;
|
||||
mod market;
|
||||
mod minimum_size;
|
||||
mod neg_risk;
|
||||
mod open_interest;
|
||||
mod portfolio;
|
||||
|
||||
@@ -29,6 +29,7 @@ pub(crate) fn apply(
|
||||
listing,
|
||||
resolution,
|
||||
taker_fee_rate_ppm,
|
||||
min_order_size,
|
||||
} => {
|
||||
identifier(&market)?;
|
||||
ensure!(!rules.trim().is_empty(), "rules required");
|
||||
@@ -36,6 +37,9 @@ pub(crate) fn apply(
|
||||
"INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')",
|
||||
params![market, rules],
|
||||
)?;
|
||||
if let Some(size) = min_order_size {
|
||||
crate::minimum_size::MinimumSize::configure(tx, &market, &size)?;
|
||||
}
|
||||
if let Some(rate) = taker_fee_rate_ppm {
|
||||
crate::fees::configure(tx, &market, rate)?;
|
||||
}
|
||||
|
||||
@@ -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(µs),
|
||||
"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(())
|
||||
}
|
||||
}
|
||||
@@ -255,3 +255,8 @@ CREATE TABLE IF NOT EXISTS order_heartbeats (
|
||||
PRIMARY KEY(account,key_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS heartbeat_deadlines ON order_heartbeats(deadline_ms);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS market_minimum_sizes (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id),
|
||||
microshares INTEGER NOT NULL CHECK(microshares BETWEEN 1 AND 1000000000000000)
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user