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: 拒绝请求,保留账户余额与挂单 E-->>C: 拒绝请求,保留账户余额与挂单
end 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 account: String,
pub key_id: Option<String>, pub key_id: Option<String>,
pub amount_cents: i64, pub amount_cents: i64,
pub max_price: i64, pub max_price: Option<i64>,
pub tif: TimeInForce, pub tif: TimeInForce,
} }
@@ -188,15 +188,16 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
identifier(&account)?; identifier(&account)?;
amount(amount_cents)?; amount(amount_cents)?;
phase(tx, &market, &["continuous"])?; phase(tx, &market, &["continuous"])?;
ensure!( ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome");
matches!(outcome.as_str(), "YES" | "NO")
&& (0..=crate::tick_size::PAR).contains(&max_price),
"invalid outcome or price"
);
ensure!( ensure!(
matches!(tif, TimeInForce::Fak | TimeInForce::Fok), matches!(tif, TimeInForce::Fak | TimeInForce::Fok),
"market buy requires FAK or 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)?; let rate = crate::fees::rate(tx, &market)?;
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? { if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
minimum.check_budget(amount_cents, max_price, rate)?; 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 { if let Some(amounts) = amounts {
receipt["order_amounts"] = amounts.json(); receipt["order_amounts"] = amounts.json();
} }
receipt["protection_price_micros"] = json!(max_price * crate::tick_size::PRICE_MICROS);
if fee > 0 || spent % 10000 != 0 { if fee > 0 || spent % 10000 != 0 {
receipt["fee_micros"] = json!(fee); receipt["fee_micros"] = json!(fee);
receipt["unspent_micros"] = json!(unspent_micros); receipt["unspent_micros"] = json!(unspent_micros);
+26 -22
View File
@@ -65,34 +65,36 @@ impl Request {
), ),
}; };
let tick = crate::tick_size::TickSize::load(tx, &market)?; 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); let tif = tif.unwrap_or(TimeInForce::Fak);
ensure!( ensure!(
matches!(tif, TimeInForce::Fak | TimeInForce::Fok), matches!(tif, TimeInForce::Fak | TimeInForce::Fok),
"estimate requires FAK or FOK" "estimate requires FAK or FOK"
); );
ensure!( ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome");
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)?;
phase(tx, &market, &["continuous"])?; 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)?; let changes = books.changes(tx)?;
books.apply(changes); 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. // The hypothetical incoming order follows all resting orders in time priority.
let mut fills = books let mut fills = books
.get(&market, &outcome) .get(&market, &outcome)
@@ -117,7 +119,8 @@ impl Request {
} else { } else {
0 0
}; };
let fully_fillable = match side { let fully_fillable = protection.is_some()
&& match side {
Side::Buy => remaining_cash == 0, Side::Buy => remaining_cash == 0,
Side::Sell => requested == shares, Side::Sell => requested == shares,
}; };
@@ -126,7 +129,8 @@ impl Request {
"worst_fill_price":fills.last().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)), "average_price_micros":(i128::from(gross)*100).checked_div(i128::from(shares)),
"fee_micros":fee,"taker_fee_rate_ppm":rate, "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 { if let Some(amounts) = amounts {
result["order_amounts"] = amounts.json(); result["order_amounts"] = amounts.json();
} }
+8 -2
View File
@@ -179,7 +179,12 @@ pub(crate) fn apply(
"market sell requires FAK or FOK" "market sell requires FAK or FOK"
); );
let qty = crate::lots::amount(qty, size_micros)?; 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 tick = crate::tick_size::TickSize::load(tx, &market)?;
let amounts = crate::market_amounts::Amounts::for_order( let amounts = crate::market_amounts::Amounts::for_order(
tick.as_ref(), tick.as_ref(),
@@ -207,6 +212,7 @@ pub(crate) fn apply(
if let Some(amounts) = amounts { if let Some(amounts) = amounts {
receipt["order_amounts"] = amounts.json(); receipt["order_amounts"] = amounts.json();
} }
receipt["protection_price_micros"] = json!(price * crate::tick_size::PRICE_MICROS);
receipt["proceeds_cents"] = receipt["proceeds_cents"] =
json!(crate::inventory::decimal(result.gross_micros.into(), 10000)); json!(crate::inventory::decimal(result.gross_micros.into(), 10000));
receipt["unsold_shares"] = json!(crate::lots::display(qty - result.filled)); receipt["unsold_shares"] = json!(crate::lots::display(qty - result.filled));
@@ -234,7 +240,7 @@ pub(crate) fn apply(
account, account,
key_id, key_id,
amount_cents: crate::market_amounts::cash_cents(amount_cents, amount_micros)?, 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), tif: tif.unwrap_or(crate::command::TimeInForce::Fak),
}, },
), ),
+36
View File
@@ -43,6 +43,42 @@ impl Books {
self.markets.get(market)?.get(outcome) 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> { pub fn recover(tx: &Transaction) -> Result<Self> {
let mut books = Self::default(); let mut books = Self::default();
let mut stmt = tx.prepare( 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); 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);
}
+4
View File
@@ -23,6 +23,10 @@ sequenceDiagram
alt 连续交易 alt 连续交易
B->>M: match_incoming,传入一条新订单 B->>M: match_incoming,传入一条新订单
M->>M: 从对手方最优价起遍历,同价按原序号分配 M->>M: 从对手方最优价起遍历,同价按原序号分配
else 未指定市价委托保护价
B->>M: opposing_levels,传入买卖方向
M->>M: 从最优对手价起,逐档汇总同价订单的剩余份额
M-->>B: 逐档返回价格和总量,调用方按需停止读取
else 盘中按金额买入 else 盘中按金额买入
B->>M: match_budget_buy,传入买单序号、最高价、以微美元计的总预算 B->>M: match_budget_buy,传入买单序号、最高价、以微美元计的总预算
M->>M: 在同一卖盘上逐单扣减可用预算,末档取预算可负担的最大整数单位数 M->>M: 在同一卖盘上逐单扣减可用预算,末档取预算可负担的最大整数单位数
+18
View File
@@ -42,6 +42,24 @@ impl OrderBook {
} }
} }
/// Visible opposing price levels, best first. Sum orders at one level
/// before exposing it so a client sees the same depth regardless of FIFO splits.
pub fn opposing_levels(&self, side: Side) -> impl Iterator<Item = (i64, i128)> + '_ {
let orders: Box<dyn Iterator<Item = &Order> + '_> = match side {
Side::Buy => Box::new(self.asks.values()),
Side::Sell => Box::new(self.bids.values()),
};
let mut orders = orders.peekable();
std::iter::from_fn(move || {
let first = orders.next()?;
let mut size = i128::from(first.remaining);
while let Some(order) = orders.next_if(|o| o.price == first.price) {
size += i128::from(order.remaining);
}
Some((first.price, size))
})
}
/// Buy integer lots at maker prices. Express the budget in price ticks /// Buy integer lots at maker prices. Express the budget in price ticks
/// multiplied by quantity lots, the same units as price * remaining. /// multiplied by quantity lots, the same units as price * remaining.
pub fn match_budget_buy(&self, seq: i64, limit: i64, budget: i64) -> Vec<Fill> { pub fn match_budget_buy(&self, seq: i64, limit: i64, budget: i64) -> Vec<Fill> {
+13
View File
@@ -0,0 +1,13 @@
{"op":"list","id":"list","market":"fixture","rules":"Simulated result","tick_size":"0.01"}
{"op":"fund","id":"a","account":"maker","cents":2000}
{"op":"fund","id":"b","account":"taker","cents":1000}
{"op":"split","id":"mint","market":"fixture","account":"maker","qty":7}
{"op":"open","id":"start","market":"fixture"}
{"op":"order","id":"ordinary","asset_id":"eb:YES:fixture","account":"maker","side":"sell","price":40,"qty":2}
{"op":"order","id":"complement","asset_id":"eb:NO:fixture","account":"maker","side":"buy","price":50,"qty":3}
{"op":"estimate","asset_id":"eb:YES:fixture","side":"buy","amount_cents":231,"tif":"FOK"}
{"op":"estimate","asset_id":"eb:YES:fixture","side":"buy","amount_cents":231,"tif":"FAK"}
{"op":"market_buy","id":"take","asset_id":"eb:YES:fixture","account":"taker","amount_cents":180,"tif":"FOK"}
{"op":"order","id":"bid-low","asset_id":"eb:YES:fixture","account":"maker","side":"buy","price":20,"qty":2}
{"op":"order","id":"bid-high","asset_id":"eb:YES:fixture","account":"maker","side":"buy","price":30,"qty":2}
{"op":"market_sell","id":"sell","asset_id":"eb:YES:fixture","account":"taker","qty":3,"tif":"FOK"}
+8
View File
@@ -279,3 +279,11 @@ order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可
配置价格步长后,`market_amounts` 读出保护价对应的 `makerAmount` 与 `takerAmount`。买单用 `amount_cents` 或 `amount_micros` 指定预算,向下取整到美分。卖单用 `qty` 或 `size_micros` 指定份额,向下取整到 0.01 份。显式保护价必须落在市场网格上。买单编码的有效价格若达到用户上限加 0.0001,预览、估价和下单均拒绝。成交估价及真实模拟成交回执通过 `order_amounts` 给出相同口径。估价还考虑当时盘口、手续费和本地可成交单位。[官方市价单金额计算](https://docs.polymarket.com/trading/place-orders.md) 配置价格步长后,`market_amounts` 读出保护价对应的 `makerAmount` 与 `takerAmount`。买单用 `amount_cents` 或 `amount_micros` 指定预算,向下取整到美分。卖单用 `qty` 或 `size_micros` 指定份额,向下取整到 0.01 份。显式保护价必须落在市场网格上。买单编码的有效价格若达到用户上限加 0.0001,预览、估价和下单均拒绝。成交估价及真实模拟成交回执通过 `order_amounts` 给出相同口径。估价还考虑当时盘口、手续费和本地可成交单位。[官方市价单金额计算](https://docs.polymarket.com/trading/place-orders.md)
[回放样例](examples/market-amounts.jsonl)先预览 10 美元预算在最高价 0.52 下的 19.2307 份编码,再按 0.50 卖盘买到 20 份。随后卖出 5.01 份,最低接受 0.48 美元,实际按 0.50 美元得到 2.505 美元。本地成交的最小数量单位仍是 0.01 份。这里复现公开委托金额公式,真实签名、生产成交粒度与资金到账仍待对照。 [回放样例](examples/market-amounts.jsonl)先预览 10 美元预算在最高价 0.52 下的 19.2307 份编码,再按 0.50 卖盘买到 20 份。随后卖出 5.01 份,最低接受 0.48 美元,实际按 0.50 美元得到 2.505 美元。本地成交的最小数量单位仍是 0.01 份。这里复现公开委托金额公式,真实签名、生产成交粒度与资金到账仍待对照。
## 由对手盘口推导市价单保护价
省略最高买价或最低卖价时,使用当前交易品盘口的价格优先顺序。买单逐档累计金额,卖单逐档累计份额,首次达到请求量的一档给出保护价。FAK 在深度不足时取最远可见档。FOK 在深度不足时无法生成委托。空盘两种模式都无法自动定价。估价用 `protection_price_micros: null` 和 `executable: false` 表示无法定价,并返回可见的部分深度。显式保护价继续生效。[官方 Python CLOB v2 定价实现(固定版本)](https://github.com/Polymarket/py-clob-client-v2/blob/9c7c9e89cbbc11528daae90dc66ef65c9380cbdf/py_clob_client_v2/order_builder/builder.py#L307-L351)
[本地回放样例](examples/depth-protection.jsonl)包含普通 YES 卖单和 NO 买单映射出的 YES 卖盘。定价使用费用前的订单簿深度,实际成交另行检查预算、费用和本地数量精度。保护价只对该次读取的盘口有效,提交请求时会重新读取。客户端可显式提交预览过的保护价。相同请求号的重试返回已保存的原始回执。
在固定版本的官方 Python 函数上实测,若依次有 0.10、0.70、0.90 美元各一份卖盘,0.80 美元预算会得到 0.90 美元保护价。原因是前两档的二进制浮点和略低于 0.80。本地在推导委托保护价时复现这一可观察结果,成交和扣款仍按整数计算,两份合计恰好 0.80 美元。样例未向生产环境发单。