Validate per-market minimum share size on order entry and previews
This commit is contained in:
@@ -44,6 +44,12 @@ flowchart LR
|
||||
queries -->|市价预估| estimate["src/estimate.rs"]
|
||||
estimate -->|同步并读取常驻盘口| cache
|
||||
estimate -->|成交金额| book
|
||||
market -->|上架时保存起订份额| minimum["src/minimum_size.rs"]
|
||||
book -->|检查提交量| minimum
|
||||
estimate -->|检查提交量与预算| minimum
|
||||
queries -->|展示盘口起订份额| minimum
|
||||
assets -->|展示交易约束| minimum
|
||||
minimum -->|保护价费用| fees
|
||||
estimate -->|含费预算| fees["src/fees.rs"]
|
||||
book -->|记录吃单手续费并扣款| fees
|
||||
market -->|上架费率| fees
|
||||
@@ -581,3 +587,24 @@ sequenceDiagram
|
||||
E->>D: 撤销该账户与 key 的活跃余单,释放预留并更新报价
|
||||
E->>E: 根据已提交的订单变更同步常驻盘口
|
||||
```
|
||||
|
||||
## 按盘口检查最小提交量
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
participant B as 常驻订单簿
|
||||
C->>E: 查询 book 或 assets
|
||||
E-->>C: 返回最小份额
|
||||
C->>E: 提交委托或市价预估
|
||||
E->>D: 在当前事务读取该盘门槛
|
||||
alt 份数或保护价下的预算不足
|
||||
E-->>C: 返回门槛错误
|
||||
else 达标
|
||||
E->>B: 按价格、时间和订单类型撮合或预估
|
||||
B-->>E: 返回可成交数量,包括小于门槛的余单成交
|
||||
E-->>C: 回执或预估结果
|
||||
end
|
||||
```
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
|
||||
@@ -2001,3 +2001,67 @@ fn heartbeat_rotates_and_recovers_only_orders_owned_by_the_expired_key() {
|
||||
assert_eq!(s["orders"][3]["status"], "live");
|
||||
assert_eq!(s["orders"][5]["status"], "live");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimum_size_checks_submitted_orders_and_preserves_partial_fills() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("minimum.db");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
for line in include_str!("../../../docs/examples/minimum-size.jsonl").lines() {
|
||||
let cmd: Value = serde_json::from_str(line).unwrap();
|
||||
let result = e.execute(cmd.clone()).unwrap();
|
||||
if cmd["id"] == "first" {
|
||||
assert_eq!(result["filled"], 5);
|
||||
}
|
||||
if cmd["op"] == "book" {
|
||||
assert_eq!(result["asks"][0]["size"], 3);
|
||||
assert_eq!(result["min_order_size"], "5");
|
||||
}
|
||||
if cmd["id"] == "second" {
|
||||
assert_eq!(result["filled"], 3);
|
||||
}
|
||||
}
|
||||
drop(e);
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
assert_eq!(
|
||||
e.execute(json!({"op":"assets","market":"e"})).unwrap()["min_order_size"],
|
||||
"5"
|
||||
);
|
||||
let before = state(&mut e);
|
||||
for cmd in [
|
||||
order("small", "bob", "buy", 55, 4),
|
||||
json!({"op":"market_sell","id":"small-sell","market":"e","account":"alice","outcome":"YES","qty":4,"min_price":1}),
|
||||
json!({"op":"market_buy","id":"small-buy","market":"e","account":"bob","outcome":"YES","amount_cents":259,"max_price":52}),
|
||||
json!({"op":"estimate","asset_id":"eb:YES:e","side":"buy","amount_cents":259,"max_price":52}),
|
||||
json!({"op":"estimate","asset_id":"eb:NO:e","side":"sell","qty":4}),
|
||||
] {
|
||||
assert!(e
|
||||
.execute(cmd)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("min_order_size"));
|
||||
}
|
||||
assert_eq!(state(&mut e), before);
|
||||
let empty=e.execute(json!({"op":"estimate","asset_id":"eb:YES:e","side":"buy","amount_cents":260,"max_price":52})).unwrap();
|
||||
assert_eq!(empty["filled_shares"], 0);
|
||||
|
||||
e.execute(json!({"op":"list","id":"fractional","market":"f","rules":"r","min_order_size":"5.125000","taker_fee_rate_ppm":50000})).unwrap();
|
||||
assert_eq!(
|
||||
e.execute(json!({"op":"assets","market":"f"})).unwrap()["min_order_size"],
|
||||
"5.125"
|
||||
);
|
||||
e.execute(json!({"op":"open","id":"open-f","market":"f"}))
|
||||
.unwrap();
|
||||
for (budget, ok) in [(307, false), (308, true)] {
|
||||
let quote=e.execute(json!({"op":"estimate","market":"f","outcome":"YES","side":"buy","max_price":50,"amount_cents":budget}));
|
||||
assert_eq!(quote.is_ok(), ok);
|
||||
}
|
||||
let invalid = json!({"op":"list","id":"retry","market":"invalid","rules":"r","min_order_size":"0.0000001"});
|
||||
assert!(e.execute(invalid).is_err());
|
||||
e.execute(json!({"op":"list","id":"retry","market":"invalid","rules":"r"}))
|
||||
.unwrap();
|
||||
assert!(e
|
||||
.execute(json!({"op":"assets","market":"invalid"}))
|
||||
.unwrap()["min_order_size"]
|
||||
.is_null());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user