Derive market order protection from visible opposing depth

This commit is contained in:
2026-12-03 07:18:25 +08:00
parent f90605bfc7
commit 5d82be0091
10 changed files with 201 additions and 33 deletions
+18
View File
@@ -858,3 +858,21 @@ sequenceDiagram
E-->>C: 拒绝请求,保留账户余额与挂单
end
```
### 市价单按盘口深度定价
```mermaid
sequenceDiagram
participant C as 客户端
participant E as estimate.rs 或 market.rs 与 book.rs
participant R as resident.rs
participant B as matching 盘口
C->>E: 买入 1.80 美元,省略最高价
E->>R: 用本事务已同步的 YES 盘口计算保护价
R->>B: 读取最优价起的卖盘档位
B-->>R: 0.40 有 2 份,0.50 有 3 份
R->>R: 累计金额,第二档覆盖 1.80 美元
R-->>E: 保护价 0.50,包含互补 NO 买单形成的卖盘
E->>B: 用预算和保护价计算可成交数量
E-->>C: 估价返回预期成交,下单提交成功后返回实际成交
```
+8 -6
View File
@@ -171,7 +171,7 @@ pub(crate) struct BudgetBuy {
pub account: String,
pub key_id: Option<String>,
pub amount_cents: i64,
pub max_price: i64,
pub max_price: Option<i64>,
pub tif: TimeInForce,
}
@@ -188,15 +188,16 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
identifier(&account)?;
amount(amount_cents)?;
phase(tx, &market, &["continuous"])?;
ensure!(
matches!(outcome.as_str(), "YES" | "NO")
&& (0..=crate::tick_size::PAR).contains(&max_price),
"invalid outcome or price"
);
ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome");
ensure!(
matches!(tif, TimeInForce::Fak | TimeInForce::Fok),
"market buy requires FAK or FOK"
);
let max_price = books
.protection_price(&market, &outcome, Side::Buy, amount_cents, max_price, tif)
.ok_or_else(|| {
anyhow::anyhow!("insufficient opposing depth for market buy protection price")
})?;
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)?;
@@ -254,6 +255,7 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
if let Some(amounts) = amounts {
receipt["order_amounts"] = amounts.json();
}
receipt["protection_price_micros"] = json!(max_price * crate::tick_size::PRICE_MICROS);
if fee > 0 || spent % 10000 != 0 {
receipt["fee_micros"] = json!(fee);
receipt["unspent_micros"] = json!(unspent_micros);
+29 -25
View File
@@ -65,34 +65,36 @@ impl Request {
),
};
let tick = crate::tick_size::TickSize::load(tx, &market)?;
let edge = tick.as_ref().map_or(0, |t| i64::from(t.local_step().get()));
let limit = limit.unwrap_or(if side == Side::Buy {
crate::tick_size::PAR - edge
} else {
edge
});
let tif = tif.unwrap_or(TimeInForce::Fak);
ensure!(
matches!(tif, TimeInForce::Fak | TimeInForce::Fok),
"estimate requires FAK or FOK"
);
ensure!(
matches!(outcome.as_str(), "YES" | "NO")
&& (0..=crate::tick_size::PAR).contains(&limit),
"invalid outcome or price"
);
let amounts =
crate::market_amounts::Amounts::for_order(tick.as_ref(), side, requested, limit)?;
ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome");
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_microshares(requested * crate::lots::MICROS)?,
}
}
let changes = books.changes(tx)?;
books.apply(changes);
let protection = books.protection_price(&market, &outcome, side, requested, limit, tif);
let amounts = match protection {
Some(price) => {
crate::market_amounts::Amounts::for_order(tick.as_ref(), side, requested, price)?
}
None => None,
};
let rate = crate::fees::rate(tx, &market)?;
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
match (side, protection) {
(Side::Buy, Some(price)) => minimum.check_budget(requested, price, rate)?,
(Side::Sell, _) => minimum.check_microshares(requested * crate::lots::MICROS)?,
(Side::Buy, None) => {}
}
}
// A failed FOK estimate still reports how much depth was visible.
let limit = protection.unwrap_or(if side == Side::Buy {
crate::tick_size::PAR
} else {
0
});
// The hypothetical incoming order follows all resting orders in time priority.
let mut fills = books
.get(&market, &outcome)
@@ -117,16 +119,18 @@ impl Request {
} else {
0
};
let fully_fillable = match side {
Side::Buy => remaining_cash == 0,
Side::Sell => requested == shares,
};
let fully_fillable = protection.is_some()
&& match side {
Side::Buy => remaining_cash == 0,
Side::Sell => requested == shares,
};
let mut result = json!({"asset_id":assets::id(&market,&outcome),"filled_shares":crate::lots::display(shares),
"gross_cents":crate::inventory::decimal(gross.into(),10000),"best_fill_price":fills.first().map(|f|crate::inventory::decimal(f.price.into(),100)),
"worst_fill_price":fills.last().map(|f|crate::inventory::decimal(f.price.into(),100)),
"average_price_micros":(i128::from(gross)*100).checked_div(i128::from(shares)),
"fee_micros":fee,"taker_fee_rate_ppm":rate,
"fully_fillable":fully_fillable,"executable":shares>0 && (tif==TimeInForce::Fak || fully_fillable)});
"protection_price_micros":protection.map(|p|p * crate::tick_size::PRICE_MICROS),
"fully_fillable":fully_fillable,"executable":protection.is_some() && shares>0 && (tif==TimeInForce::Fak || fully_fillable)});
if let Some(amounts) = amounts {
result["order_amounts"] = amounts.json();
}
+8 -2
View File
@@ -179,7 +179,12 @@ pub(crate) fn apply(
"market sell requires FAK or FOK"
);
let qty = crate::lots::amount(qty, size_micros)?;
let price = crate::tick_size::required(min_price, min_price_micros)?;
let limit = crate::tick_size::input(min_price, min_price_micros)?;
let price = books
.protection_price(&market, &outcome, matching::Side::Sell, qty, limit, tif)
.ok_or_else(|| {
anyhow::anyhow!("insufficient opposing depth for market sell protection price")
})?;
let tick = crate::tick_size::TickSize::load(tx, &market)?;
let amounts = crate::market_amounts::Amounts::for_order(
tick.as_ref(),
@@ -207,6 +212,7 @@ pub(crate) fn apply(
if let Some(amounts) = amounts {
receipt["order_amounts"] = amounts.json();
}
receipt["protection_price_micros"] = json!(price * crate::tick_size::PRICE_MICROS);
receipt["proceeds_cents"] =
json!(crate::inventory::decimal(result.gross_micros.into(), 10000));
receipt["unsold_shares"] = json!(crate::lots::display(qty - result.filled));
@@ -234,7 +240,7 @@ pub(crate) fn apply(
account,
key_id,
amount_cents: crate::market_amounts::cash_cents(amount_cents, amount_micros)?,
max_price: crate::tick_size::required(max_price, max_price_micros)?,
max_price: crate::tick_size::input(max_price, max_price_micros)?,
tif: tif.unwrap_or(crate::command::TimeInForce::Fak),
},
),
+36
View File
@@ -43,6 +43,42 @@ impl Books {
self.markets.get(market)?.get(outcome)
}
/// The cash input to an exchange command is in cents, the share input in lots.
pub fn protection_price(
&self,
market: &str,
outcome: &str,
side: Side,
requested: i64,
limit: Option<i64>,
tif: crate::command::TimeInForce,
) -> Option<i64> {
limit.or_else(|| {
// The reference Python SDK sums one binary64 value per public
// price level, in dollars (BUY) or shares (SELL). Match its limit
// selection here; all execution and settlement use integer units.
let target = requested as f64 / 100.0;
let mut depth = 0.0;
let mut last = None;
for (price, lots) in self.get(market, outcome)?.opposing_levels(side) {
let shares = lots as f64 / crate::lots::PER_SHARE as f64;
depth += match side {
Side::Buy => shares * (price as f64 / crate::tick_size::PAR as f64),
Side::Sell => shares,
};
last = Some(price);
if depth >= target {
return last;
}
}
if tif == crate::command::TimeInForce::Fak {
last
} else {
None
}
})
}
pub fn recover(tx: &Transaction) -> Result<Self> {
let mut books = Self::default();
let mut stmt = tx.prepare(
+59
View File
@@ -2686,3 +2686,62 @@ fn unsafe_encoded_buy_is_rejected_by_preview_estimate_and_submission() {
}
assert_eq!(state(&mut e), before);
}
#[test]
fn derives_protection_from_current_depth_and_replays_the_original_receipt() {
let dir = tempdir().unwrap();
let path = dir.path().join("book.db");
let mut writer = Exchange::open(&path).unwrap();
let mut client = Exchange::open(&path).unwrap();
for line in include_str!("../../../docs/examples/depth-protection.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
match cmd["op"].as_str().unwrap() {
"estimate" => {
let result = client.execute(cmd.clone()).unwrap();
assert_eq!(result["filled_shares"], 5);
if cmd["tif"] == "FOK" {
assert!(result["protection_price_micros"].is_null());
assert_eq!(result["executable"], false);
let before = state(&mut client);
assert!(client.execute(json!({"op":"market_buy","id":"short","asset_id":"eb:YES:fixture","account":"taker","amount_cents":231,"tif":"FOK"})).is_err());
assert_eq!(state(&mut client), before);
} else {
assert_eq!(result["protection_price_micros"], 500000);
assert_eq!(result["executable"], true);
}
}
"market_buy" => {
let r = client.execute(cmd.clone()).unwrap();
assert_eq!(r["protection_price_micros"], 500000);
assert_eq!(r["filled"], 4);
assert_eq!(r["spent_cents"], 180);
drop(client);
client = Exchange::open(&path).unwrap();
assert_eq!(client.execute(cmd).unwrap(), r);
}
"market_sell" => {
let r = client.execute(cmd).unwrap();
assert_eq!(r["protection_price_micros"], 200000);
assert_eq!(r["proceeds_cents"], 80);
}
_ => {
writer.execute(cmd).unwrap();
}
}
}
}
#[test]
fn automatic_price_uses_sdk_level_precision_while_cash_execution_is_exact() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"open","market":"e"}))
.unwrap();
for (id, price) in [("a10", 10), ("a70", 70), ("a90", 90)] {
e.execute(order(id, "alice", "sell", price, 1)).unwrap();
}
let r = e.execute(json!({"op":"market_buy","id":"depth","market":"e","outcome":"YES","account":"bob","amount_cents":80,"tif":"FOK"})).unwrap();
assert_eq!(r["protection_price_micros"], 900000);
assert_eq!(r["spent_cents"], 80);
assert_eq!(r["filled"], 2);
}