市场成交与持仓数据及含吃单手续费的本地交割 #7
@@ -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());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{"op":"list","id":"list","market":"e","rules":"模拟赛事官方结果","min_order_size":"5"}
|
||||
{"op":"fund","id":"a","account":"alice","cents":2000}
|
||||
{"op":"fund","id":"b","account":"bob","cents":2000}
|
||||
{"op":"split","id":"split","market":"e","account":"alice","qty":8}
|
||||
{"op":"order","id":"ask","market":"e","outcome":"YES","side":"sell","price":52,"qty":8,"account":"alice"}
|
||||
{"op":"open","id":"open","market":"e"}
|
||||
{"op":"order","id":"first","market":"e","outcome":"YES","side":"buy","price":52,"qty":5,"account":"bob"}
|
||||
{"op":"book","asset_id":"eb:YES:e"}
|
||||
{"op":"market_buy","id":"second","market":"e","outcome":"YES","account":"bob","amount_cents":260,"max_price":52,"tif":"FAK"}
|
||||
@@ -208,3 +208,11 @@ FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高
|
||||
停止续期并保持 CLI 打开,10 秒阈值过后,下一次 5 秒定时检查或下一条有效交易/查询会撤掉同一账户、同一 key 在各盘口的 live 余单,释放现金及份额预留。用 open_orders 核对结果。同账户的其他 key 和其他账户同名 key 的订单各自独立。过期注册被移除,新挂单需要新的成功心跳才能重新获得保护。旧订单及省略 key_id 的订单属于该账户的默认 key,给默认 key 发送心跳时省略 key_id。关闭整个本地进程后,到期清理由其他活跃实例或重启时完成。
|
||||
|
||||
本地 key_id 是可信模拟命令中的所有权标识。官方依据已认证凭据判定所有权,在扫描时排队尽力撤单。本地在同一 SQLite 事务内移除注册、撤单并释放预留;独立嵌入 exchange 的宿主可调用 maintain 驱动空闲期检查。鉴权、生产队列延迟和失败时的逐单结果仍待实测。
|
||||
|
||||
## 最小下单量
|
||||
|
||||
官方下单示例从 CLOB 的 book 读取 min_order_size="5",按结果份额检查订单规模。市价买单的提交数量取决于金额和最高可接受价。Gamma 市场详情文档另将 orderMinSize 描述为 USDC 名义金额;将外场元数据导入本地时,两者的真实映射仍须同一盘口的接口响应及订单验收来核对。[官方下单与订单金额](https://docs.polymarket.com/trading/place-orders.md) · [官方市场交易约束](https://docs.polymarket.com/market-data/market-details.md)
|
||||
|
||||
[可重放样例](examples/minimum-size.jsonl)上架时设置 min_order_size="5"。卖家挂 8 份,第一张 5 份买单成交后余下 3 份,仍可在盘口看到。第二张 FAK 买单给定预算 2.60 模拟美元、保护价 0.52,达到提交 5 份的门槛,可成交剩余 3 份。若改为 2.59 则在预留资金前拒绝。卖单和按份数发出的限价单检查提交份数;盘前、盘中、YES 与 NO 接受同一门槛。撤单、逐笔成交和存量余额沿用原有语义。
|
||||
|
||||
list 接受十进制份额字符串,最多六位小数;book、assets 和事件 catalog 返回去掉多余末尾零的字符串。没有配置的旧市场返回 null,继续适用原有数量与预算逻辑。本地只能交易整份,门槛 5.125 的最小可提交份数为 6。预算买单用保护价和这一起订份数计算最低预算,并计入该价位的一笔吃单费。例如保护价 0.50、费率 0.05 时,六份需要 3.075 模拟美元,分为单位的预算至少 3.08。这个含费门槛、部分成交余量与生产舍入方式仍待外场比对。
|
||||
|
||||
Reference in New Issue
Block a user