Compare commits

...

2 Commits

16 changed files with 397 additions and 68 deletions
+13
View File
@@ -167,12 +167,16 @@ CTF 市场可在任一结果资产映射中填写 `condition_id`(32 字节十
下单回执返回整数字符串字段 `makingAmount` 和 `takingAmount`,单位是百万分之一美元或份额,以买卖方向决定顺序。首次提交时只有挂单,返回签名条款和 `live`。发生即时成交时,返回实际成交本金、份额、`tradeIDs` 和 `matched`。部分成交后仍在盘口的剩余量可从订单查询读取。相同请求的重试只返回首次提交产生的成交。模拟成交没有链上交易哈希。[官方下单回执](https://docs.polymarket.com/trading/place-orders#check-the-response)
签名市价买单按 `makerAmount` 的整数微美元预留预算。[不足一美分的签名样例](../../docs/examples/signed-ctf-micro-budget.json) 在 0.013 美元的零费卖盘上花费 4940 微美元买到 0.38 份,退回 60 微美元。
启用了秒级撮合延迟的市场中,可立即成交的签名订单先收到 `delayed`。按订单哈希可查询等待或拒绝状态,等待期间的撤单响应会说明该订单仍在延迟窗口。订单到期后进入平常的撮合流程,所得成交仍通过账户频道和成交查询发送。账户 HTTP 服务每 250 毫秒检查到期订单,重启后继续处理数据库里已受理的订单。[官方订单生命周期](https://docs.polymarket.com/concepts/order-lifecycle)
若市场详情显示 `itode: true`,可立即成交的订单进入 150 毫秒等待。HTTP 在账本锁外等待,并在重新校验后返回最终回执。批量回执保持输入顺序,只等待其中的 `itode` 订单。若服务暂时读不到执行结果,返回 HTTP 503;客户端可重送相同签名订单查询原处理结果。[官方订单生命周期](https://docs.polymarket.com/concepts/order-lifecycle)
`POST /orders` 接受最多 15 笔签名订单组成的 JSON 数组。对整个数组的原始请求体验签,再逐项验订单签名。本地按输入顺序受理,结果数组与输入对齐,单项失败时其余有效订单继续提交。[官方批量接口](https://docs.polymarket.com/api-reference/trade/post-multiple-orders)
单笔和批量订单省略 `orderType` 时按 GTC 处理。同一签名订单显式传 GTC 时沿用同一回执。同步延迟期间若对手撤单,受理后实际进入盘口的订单返回 `live`,金额采用原限价条款。
```mermaid
flowchart LR
main["main.rs"] --> http["account_http.rs"]
@@ -223,6 +227,7 @@ sequenceDiagram
H-->>C: HTTP 401
else 提交签名订单
H->>V: 提交订单、API key 与已认证的签名者地址
V->>V: 省略 orderType 时使用 GTC
V->>V: 按 tokenId 查找资产、EIP-712 域并核对钱包绑定
alt 合约钱包
V->>R: eth_call isValidSignature(hash, signature)
@@ -232,8 +237,16 @@ sequenceDiagram
end
alt 验证通过
V->>E: 以订单哈希为幂等键提交本地订单与已验签 maker
opt 签名市价买单
V->>E: 传递有零头的完整微美元预算
end
E-->>V: 返回挂单、即时成交或 delayed 回执
V-->>H: 返回订单状态、资产数量和即时成交 ID
opt 等待同步延迟回执
H->>V: 按订单哈希读取最终结果
V->>E: 读取首次提交成交,若实际挂单则读取原限价数量
V-->>H: 返回 live 或 matched 等最终状态
end
else 验证失败
V-->>H: 返回订单拒绝
end
+199 -19
View File
@@ -387,20 +387,32 @@ fn placement_response(
.as_i64()
.context("missing signed order number")?;
let fills = engine.submission_fills(order)?;
let (status, making, taking) = if fills.trade_ids.is_empty() {
match signed_amounts {
Some((making, taking)) if receipt["status"] == "live" => ("live", making, taking),
_ => ("unmatched", String::new(), String::new()),
}
} else {
let cash = fills.cash_micros.to_string();
let shares = fills.shares_micros.to_string();
let wire_amounts = |cash: i128, shares: i128| {
if selling {
("matched", shares, cash)
(shares.to_string(), cash.to_string())
} else {
("matched", cash, shares)
(cash.to_string(), shares.to_string())
}
};
let (status, (making, taking)) = if !fills.trade_ids.is_empty() {
(
"matched",
wire_amounts(fills.cash_micros, fills.shares_micros),
)
} else if receipt["status"] == "live" {
let amounts = match signed_amounts {
Some(amounts) => amounts,
None => {
// A synchronous order may stop crossing before release and rest
// instead. The accepted order retains the exact limit amounts.
let (cash, shares) = engine.submission_amounts(order)?;
wire_amounts(cash, shares)
}
};
("live", amounts)
} else {
("unmatched", (String::new(), String::new()))
};
let trade_ids: Vec<_> = fills
.trade_ids
.into_iter()
@@ -437,13 +449,35 @@ pub(crate) fn rejected_order() -> Value {
struct Request {
owner: String,
order: Order,
order_type: String,
#[serde(default)]
order_type: OrderType,
#[serde(default)]
post_only: bool,
#[serde(default)]
defer_exec: bool,
}
#[derive(Clone, Copy, Default, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
enum OrderType {
#[default]
Gtc,
Gtd,
Fak,
Fok,
}
impl OrderType {
fn as_str(self) -> &'static str {
match self {
Self::Gtc => "GTC",
Self::Gtd => "GTD",
Self::Fak => "FAK",
Self::Fok => "FOK",
}
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Order {
@@ -561,10 +595,6 @@ impl Request {
ensure!(maker > 0 && taker > 0, "invalid signed amounts");
let expiry: i64 = self.order.expiration.parse()?;
let tif = self.order_type.as_str();
ensure!(
matches!(tif, "GTC" | "GTD" | "FAK" | "FOK"),
"unsupported order type"
);
ensure!(
if tif == "GTD" {
expiry > 0
@@ -598,10 +628,15 @@ impl Request {
};
ensure!((100..1_000_000).contains(&price), "invalid signed price");
if immediate && buy {
ensure!(cash % 10_000 == 0, "market buy amount requires whole cents");
return Ok(
json!({"op":"market_buy","asset_id":asset,"amount_cents":cash / 10_000,"max_price_micros":price,"tif":tif}),
);
let mut command =
json!({"op":"market_buy","asset_id":asset,"max_price_micros":price,"tif":tif});
// Whole-cent requests keep their original shape for receipt replay.
if cash % 10_000 == 0 {
command["amount_cents"] = json!(cash / 10_000);
} else {
command["amount_micros"] = json!(cash);
}
return Ok(command);
}
ensure!(
shares % 10_000 == 0,
@@ -773,6 +808,151 @@ mod tests {
serde_json::from_str(include_str!("../../../docs/examples/signed-ctf-order.json")).unwrap()
}
#[test]
fn signed_subcent_market_buy_executes_and_replays_exactly() {
let vector: Value = serde_json::from_str(include_str!(
"../../../docs/examples/signed-ctf-micro-budget.json"
))
.unwrap();
let wallet = vector["wallet"].as_str().unwrap();
let orders =
Orders::new(serde_json::from_value(vector["order_config"].clone()).unwrap()).unwrap();
let mut engine = Exchange::open(":memory:").unwrap();
for cmd in [
json!({"op":"fund","id":"alice","account":"alice","micros":5000}),
json!({"op":"fund","id":"bob","account":"bob","cents":200}),
json!({"op":"list","id":"list","market":"demo","rules":"test","tick_size":"0.001"}),
json!({"op":"split","id":"split","account":"bob","market":"demo","qty":1}),
json!({"op":"open","id":"open","market":"demo"}),
json!({"op":"order","id":"ask","account":"bob","market":"demo","outcome":"YES","side":"sell","qty":1,"price_micros":13000}),
] {
engine.execute(cmd).unwrap();
}
let payload = vector["request"].to_string();
let mut submit = || {
orders.submit(
&mut engine,
"alice",
"alice-key",
wallet,
payload.as_bytes(),
)
};
let receipt = submit().unwrap();
assert_eq!(receipt["orderID"], vector["expected_order_hash"]);
assert_eq!(receipt["status"], "matched");
assert_eq!(receipt["makingAmount"], "4940");
assert_eq!(receipt["takingAmount"], "380000");
assert_eq!(receipt["local_receipt"]["amount_micros"], 5000);
assert_eq!(receipt["local_receipt"]["unspent_micros"], 60);
assert_eq!(submit().unwrap(), receipt);
assert_eq!(engine.wallet_balance_micros("alice", None).unwrap(), 60);
}
#[test]
fn omitted_order_type_is_gtc_in_single_and_mixed_batch_requests() {
let vector = sample();
let wallet = vector["wallet"].as_str().unwrap();
let orders =
Orders::new(serde_json::from_value(vector["order_config"].clone()).unwrap()).unwrap();
let explicit = &vector["request"];
let mut omitted = explicit.clone();
omitted.as_object_mut().unwrap().remove("orderType");
let mut invalid = omitted.clone();
invalid["orderType"] = Value::Null;
let mut engine = Exchange::open(":memory:").unwrap();
for cmd in [
json!({"op":"fund","id":"fund","account":"alice","cents":500}),
json!({"op":"list","id":"list","market":"demo","rules":"test","tick_size":"0.01"}),
json!({"op":"open","id":"open","market":"demo"}),
] {
engine.execute(cmd).unwrap();
}
let first = orders
.submit(
&mut engine,
"alice",
"alice-key",
wallet,
omitted.to_string().as_bytes(),
)
.unwrap();
assert_eq!(first["status"], "live");
assert_eq!(first["orderID"], vector["expected_order_hash"]);
let batch = json!([explicit, invalid, omitted]);
let reply = orders
.submit_batch(
&mut engine,
"alice",
"alice-key",
wallet,
batch.to_string().as_bytes(),
)
.unwrap();
assert_eq!(reply[0], first);
assert_eq!(reply[1], rejected_order());
assert_eq!(reply[2], first);
assert_eq!(
engine.execute(json!({"op":"state"})).unwrap()["orders"]
.as_array()
.unwrap()
.len(),
1
);
}
#[test]
fn synchronous_order_reports_live_if_liquidity_leaves_before_release() {
let vector = sample();
let wallet = vector["wallet"].as_str().unwrap();
let orders =
Orders::new(serde_json::from_value(vector["order_config"].clone()).unwrap()).unwrap();
let mut engine = Exchange::open(":memory:").unwrap();
for cmd in [
json!({"op":"fund","id":"alice","account":"alice","cents":500}),
json!({"op":"fund","id":"bob","account":"bob","cents":500}),
json!({"op":"list","id":"list","market":"demo","rules":"test","tick_size":"0.01"}),
json!({"op":"split","id":"split","account":"bob","market":"demo","qty":3}),
json!({"op":"open","id":"open","market":"demo"}),
json!({"op":"set_taker_delay","id":"delay","market":"demo","itode":true}),
] {
engine.execute(cmd).unwrap();
}
let ask = engine
.execute(json!({"op":"order","id":"ask","account":"bob",
"market":"demo","outcome":"YES","side":"sell","qty":3,"price":55}))
.unwrap();
let payload = vector["request"].to_string();
let queued = orders
.submit(
&mut engine,
"alice",
"alice-key",
wallet,
payload.as_bytes(),
)
.unwrap();
assert_eq!(queued["local_receipt"]["wait_for_result"], true);
engine
.execute(json!({"op":"cancel","id":"cancel","account":"bob","order":ask["order"]}))
.unwrap();
use std::time::{SystemTime, UNIX_EPOCH};
let ready = queued["local_receipt"]["ready_at_ms"].as_u64().unwrap();
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
thread::sleep(Duration::from_millis(ready.saturating_sub(now) + 1));
engine.maintain_delayed_orders().unwrap();
let hash = vector["expected_order_hash"].as_str().unwrap();
let reply = synchronous_reply(&engine, "alice", hash).unwrap().unwrap();
assert_eq!(reply["status"], "live");
assert_eq!(reply["makingAmount"], "1800000");
assert_eq!(reply["takingAmount"], "3000000");
assert_eq!(reply["tradeIDs"], json!([]));
}
fn position_sample() -> Value {
serde_json::from_str(include_str!(
"../../../docs/examples/signed-protocol-v2-orders.json"
+7 -4
View File
@@ -256,6 +256,9 @@ sequenceDiagram
D->>D: 同事务记录受影响账户的事件
opt 已验签订单
E->>D: 保存订单哈希和 maker 钱包
opt 同步延迟后挂单
E->>D: 读取原始订单价格与数量,生成挂单回执金额
end
end
alt 事务提交
opt 客户端需要建立或刷新账户状态
@@ -390,13 +393,13 @@ sequenceDiagram
participant E as Exchange
participant B as 常驻盘口
participant D as SQLite
C->>E: market_buy 指定预算分数、结果、最高价
E->>D: 写事务中预留预算,分配订单号
E->>B: 从最低卖价起按预算计划成交
C->>E: market_buy 指定预算美分或微美元、结果、最高价
E->>D: 写事务中按微美元预留预算,分配订单号
E->>B: 从最低卖价起按精确预算计划成交
alt 无可买份额或 FOK 无法用尽预算
E->>D: 回滚预留和新单
else FAK 有成交或 FOK 足额
E->>D: 逐笔交割、退回未花预算、记录回执
E->>D: 逐笔交割、退回未花预算、保存精确金额和回执
E->>B: 提交后更新受影响的盘口
E-->>C: 返回成交份数、实付与未花金额
end
+9 -6
View File
@@ -55,10 +55,11 @@ impl Filter {
let sql = format!(
"SELECT seq,market,outcome,side,price,quantity,remaining,status,
(SELECT expiration FROM order_deadlines d WHERE d.seq=orders.seq),
b.amount_cents,COALESCE((SELECT micros FROM budget_spend_micros WHERE order_seq=orders.seq),b.spent_cents*10000),
COALESCE(a.micros,b.amount_cents*10000),COALESCE((SELECT micros FROM budget_spend_micros WHERE order_seq=orders.seq),b.spent_cents*10000),
(SELECT COALESCE(SUM(fee_micros),0) FROM execution_fees WHERE taker_order=orders.seq),
(SELECT key_id FROM order_keys WHERE order_seq=orders.seq),s.order_type,s.post_only,s.created_at,w.maker_address
(SELECT key_id FROM order_keys WHERE order_seq=orders.seq),s.order_type,s.post_only,s.created_at,w.maker_address,a.micros
FROM orders LEFT JOIN budget_buys b ON b.order_seq=orders.seq
LEFT JOIN budget_amount_micros a ON a.order_seq=orders.seq
LEFT JOIN order_submissions s ON s.order_seq=orders.seq
LEFT JOIN signed_order_wallets w ON w.order_seq=orders.seq
WHERE account=?1 AND (?2 IS NULL OR market=?2) AND (?3 IS NULL OR outcome=?3)
@@ -93,8 +94,7 @@ impl Filter {
let status: String = row.get(7)?;
let market: String = row.get(1)?;
let outcome: String = row.get(2)?;
orders.push(
json!({"order":id,"market":market,"asset_id":crate::assets::id(&market,&outcome),
let mut order = json!({"order":id,"market":market,"asset_id":crate::assets::id(&market,&outcome),
"outcome":outcome,"side":row.get::<_,String>(3)?,
"price_micros":row.get::<_,i64>(4)?*100,"original_size":crate::lots::display(quantity),
"size_matched":crate::lots::display(quantity-remaining),"open_size":crate::lots::display(if status=="live"{remaining}else{0}),
@@ -102,8 +102,11 @@ impl Filter {
"order_type":row.get::<_,Option<String>>(13)?,"post_only":row.get::<_,Option<bool>>(14)?,
"created_at":row.get::<_,Option<i64>>(15)?,
"maker_address":row.get::<_,Option<String>>(16)?,
"amount_cents":row.get::<_,Option<i64>>(9)?,"spent_cents":row.get::<_,Option<i64>>(10)?.map(|v|crate::inventory::decimal(v.into(),10000)),"fee_micros":row.get::<_,i64>(11)?,"key_id":row.get::<_,Option<String>>(12)?}),
);
"amount_cents":row.get::<_,Option<i64>>(9)?.map(|v|crate::inventory::decimal(v.into(),10000)),"spent_cents":row.get::<_,Option<i64>>(10)?.map(|v|crate::inventory::decimal(v.into(),10000)),"fee_micros":row.get::<_,i64>(11)?,"key_id":row.get::<_,Option<String>>(12)?});
if let Some(amount) = row.get::<_, Option<i64>>(17)? {
order["amount_micros"] = json!(amount);
}
orders.push(order);
last_id = Some(id);
}
Ok((orders, next_after))
+28 -14
View File
@@ -1,7 +1,8 @@
use crate::{command::TimeInForce, resident::Books};
use crate::{
ledger,
validation::{amount, identifier, phase},
market_amounts::MICROS_PER_CENT,
validation::{identifier, phase},
};
use anyhow::{ensure, Result};
use matching::{Fill, Order, Side};
@@ -203,7 +204,7 @@ pub(crate) struct BudgetBuy {
pub outcome: String,
pub account: String,
pub key_id: Option<String>,
pub amount_cents: i64,
pub amount_micros: i64,
pub max_price: Option<i64>,
pub tif: TimeInForce,
}
@@ -214,12 +215,11 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
market,
outcome,
account,
amount_cents,
amount_micros,
max_price,
tif,
} = order;
identifier(&account)?;
amount(amount_cents)?;
phase(tx, &market, &["continuous"])?;
ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome");
ensure!(
@@ -227,22 +227,22 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
"market buy requires FAK or FOK"
);
let max_price = books
.protection_price(&market, &outcome, Side::Buy, amount_cents, max_price, tif)
.protection_price(&market, &outcome, Side::Buy, amount_micros, 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)?;
minimum.check_budget(amount_micros, max_price, rate)?;
}
let tick = crate::tick_size::TickSize::load(tx, &market)?;
let amounts = crate::market_amounts::Amounts::for_order(
tick.as_ref(),
Side::Buy,
amount_cents,
amount_micros,
max_price,
)?;
ledger::cash(tx, &account, -amount_cents)?;
ledger::cash_micros(tx, &account, -amount_micros)?;
tx.execute(
"INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status)
VALUES(?,?,?,'buy',?,0,0,'live')",
@@ -252,13 +252,13 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
record_submission(tx, seq, tif, false, key_id.as_deref())?;
let mut fills = books
.get(&market, &outcome)
.map(|b| b.match_budget_buy(seq, max_price, amount_cents * 10000))
.map(|b| b.match_budget_buy(seq, max_price, amount_micros))
.unwrap_or_default();
crate::fees::fit_budget(rate, &mut fills, amount_cents);
crate::fees::fit_budget(rate, &mut fills, amount_micros);
ensure!(!fills.is_empty(), "no affordable liquidity");
let quantity: i64 = fills.iter().map(|f| f.quantity).sum();
let spent = gross_micros(&fills);
let gross_remainder = amount_cents * 10000 - spent;
let gross_remainder = amount_micros - spent;
let unspent_micros = gross_remainder - crate::fees::total(rate, &fills);
ensure!(
tif != TimeInForce::Fok || unspent_micros == 0,
@@ -270,8 +270,19 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
)?;
tx.execute(
"INSERT INTO budget_buys(order_seq,amount_cents,spent_cents) VALUES(?,?,?)",
params![seq, amount_cents, spent / 10000],
params![
seq,
(amount_micros + MICROS_PER_CENT - 1) / MICROS_PER_CENT,
spent / MICROS_PER_CENT
],
)?;
let fractional_budget = amount_micros % MICROS_PER_CENT != 0;
if fractional_budget {
tx.execute(
"INSERT INTO budget_amount_micros VALUES(?,?)",
params![seq, amount_micros],
)?;
}
tx.execute(
"INSERT INTO budget_spend_micros VALUES(?,?)",
params![seq, spent],
@@ -284,12 +295,15 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
tx.execute("UPDATE orders SET status='cancelled' WHERE seq=?", [seq])?;
"cancelled"
};
let mut receipt = json!({"order":seq,"status":status,"filled":crate::lots::display(quantity),"amount_cents":amount_cents,"spent_cents":crate::inventory::decimal(spent.into(),10000),"unspent_cents":crate::inventory::decimal(unspent_micros.into(),10000)});
let mut receipt = json!({"order":seq,"status":status,"filled":crate::lots::display(quantity),"amount_cents":crate::inventory::decimal(amount_micros.into(),MICROS_PER_CENT),"spent_cents":crate::inventory::decimal(spent.into(),10000),"unspent_cents":crate::inventory::decimal(unspent_micros.into(),10000)});
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 {
if fractional_budget {
receipt["amount_micros"] = json!(amount_micros);
}
if fractional_budget || fee > 0 || spent % MICROS_PER_CENT != 0 {
receipt["fee_micros"] = json!(fee);
receipt["unspent_micros"] = json!(unspent_micros);
receipt["total_spent_micros"] = json!(spent + fee);
+3 -3
View File
@@ -43,7 +43,7 @@ impl Request {
market,
outcome,
Side::Buy,
crate::market_amounts::cash_cents(amount_cents, amount_micros)?,
crate::market_amounts::cash_micros(amount_cents, amount_micros)?,
crate::tick_size::input(max_price, max_price_micros)?,
tif,
),
@@ -99,7 +99,7 @@ impl Request {
let mut fills = books
.get(&market, &outcome)
.map(|b| match side {
Side::Buy => b.match_budget_buy(i64::MAX, limit, requested * 10000),
Side::Buy => b.match_budget_buy(i64::MAX, limit, requested),
Side::Sell => b.match_incoming(&Order {
seq: i64::MAX,
side,
@@ -115,7 +115,7 @@ impl Request {
let shares: i64 = fills.iter().map(|f| f.quantity).sum();
let gross = gross_micros(&fills);
let remaining_cash = if side == Side::Buy {
requested * 10000 - gross - fee
requested - gross - fee
} else {
0
};
+2 -2
View File
@@ -71,11 +71,11 @@ pub(crate) fn total(rate: i64, fills: &[Fill]) -> i64 {
// match_budget_buy supplies FIFO candidates under the gross cap. Stop at
// the first partially affordable maker, including its rounded fee.
pub(crate) fn fit_budget(rate: i64, fills: &mut Vec<Fill>, budget: i64) {
pub(crate) fn fit_budget(rate: i64, fills: &mut Vec<Fill>, budget_micros: i64) {
if rate == 0 {
return;
}
let mut remaining = budget * 10000;
let mut remaining = budget_micros;
let mut count = 0;
for f in fills.iter_mut() {
let cost = |qty: i64| {
+1 -1
View File
@@ -294,7 +294,7 @@ pub(crate) fn apply(
outcome,
account,
key_id,
amount_cents: crate::market_amounts::cash_cents(amount_cents, amount_micros)?,
amount_micros: crate::market_amounts::cash_micros(amount_cents, amount_micros)?,
max_price: crate::tick_size::input(max_price, max_price_micros)?,
tif: tif.unwrap_or(crate::command::TimeInForce::Fak),
},
+21 -13
View File
@@ -5,14 +5,19 @@ use rusqlite::Connection;
use serde::Deserialize;
use serde_json::{json, Value};
pub(crate) fn cash_cents(cents: Option<i64>, micros: Option<i64>) -> Result<i64> {
let cents = match (cents, micros) {
(Some(n), None) => n,
(None, Some(n)) if n > 0 => n / 10_000,
_ => anyhow::bail!("provide one positive amount_cents or amount_micros"),
};
crate::validation::amount(cents)?;
Ok(cents)
pub(crate) const MICROS_PER_CENT: i64 = 10_000;
pub(crate) fn cash_micros(cents: Option<i64>, micros: Option<i64>) -> Result<i64> {
match (cents, micros) {
(Some(n), None) => {
crate::validation::amount(n)?;
Ok(n * MICROS_PER_CENT)
}
(None, Some(n)) if (1..=1_000_000_000 * MICROS_PER_CENT).contains(&n) => Ok(n),
_ => anyhow::bail!(
"provide one positive amount_cents or amount_micros within the cash limit"
),
}
}
pub(crate) struct Amounts {
@@ -42,12 +47,15 @@ impl Amounts {
}
}
// requested is in whole cents for BUY, 0.01-share lots for SELL.
// requested is in micro-dollars for BUY, 0.01-share lots for SELL.
fn encode(tick: &TickSize, side: Side, requested: i64, price: i64) -> Result<Self> {
tick.check(price)?;
let maker = requested
.checked_mul(10_000)
.ok_or_else(|| anyhow::anyhow!("order amount overflow"))?;
let maker = match side {
Side::Buy => requested,
Side::Sell => requested
.checked_mul(lots::MICROS)
.ok_or_else(|| anyhow::anyhow!("order amount overflow"))?,
};
ensure!(maker > 0, "positive order amount required");
let scale = 1_000_000_i128;
let taker = match side {
@@ -111,7 +119,7 @@ impl Request {
market,
outcome,
Side::Buy,
cash_cents(amount_cents, amount_micros)?,
cash_micros(amount_cents, amount_micros)?,
price_micros,
),
Self::Sell {
+2 -2
View File
@@ -66,11 +66,11 @@ impl MinimumSize {
Ok(())
}
pub fn check_budget(&self, cents: i64, max_price: i64, fee_rate: i64) -> Result<()> {
pub fn check_budget(&self, budget_micros: i64, max_price: i64, fee_rate: i64) -> Result<()> {
let lots = (self.0 + crate::lots::MICROS - 1) / crate::lots::MICROS;
let required = lots * max_price + crate::fees::lot_fee(fee_rate, max_price * 100, lots);
ensure!(
cents * 10000 >= required,
budget_micros >= required,
"cash budget at protection price is below min_order_size of {} shares",
self.text()
);
+12
View File
@@ -77,6 +77,18 @@ pub(crate) fn lookup(db: &Connection, account: &str, raw: &str) -> Result<Option
}
impl Exchange {
/// Return the original cash and share amounts for an accepted limit order.
pub fn submission_amounts(&self, order: i64) -> Result<(i128, i128)> {
let mut stmt = self
.db
.prepare_cached("SELECT price,quantity FROM orders WHERE seq=?")?;
Ok(stmt.query_row([order], |row| {
let price = i128::from(row.get::<_, i64>(0)?);
let lots = i128::from(row.get::<_, i64>(1)?);
Ok((price * lots, lots * i128::from(crate::lots::MICROS)))
})?)
}
/// Only executions caused by the incoming order, excluding subsequent maker fills.
pub fn submission_fills(&self, order: i64) -> Result<SubmissionFills> {
let mut stmt = self.db.prepare_cached(
+6 -2
View File
@@ -43,7 +43,7 @@ impl Books {
self.markets.get(market)?.get(outcome)
}
/// The cash input to an exchange command is in cents, the share input in lots.
/// The cash input is in micro-dollars, the share input in lots.
pub fn protection_price(
&self,
market: &str,
@@ -57,7 +57,11 @@ impl Books {
// 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 scale = match side {
Side::Buy => crate::inventory::UNIT,
Side::Sell => crate::lots::PER_SHARE,
};
let target = requested as f64 / scale as f64;
let mut depth = 0.0;
let mut last = None;
for (price, lots) in self.get(market, outcome)?.opposing_levels(side) {
+7
View File
@@ -318,6 +318,13 @@ CREATE VIEW IF NOT EXISTS market_backing AS
SELECT m.id AS market,m.collateral*10000+COALESCE(r.micros,0) AS micros
FROM markets m LEFT JOIN collateral_remainders r ON r.market=m.id;
-- The legacy cent column rounds up to satisfy its positive integer constraint.
-- A stored micro-dollar amount is authoritative for fractional budgets.
CREATE TABLE IF NOT EXISTS budget_amount_micros (
order_seq INTEGER PRIMARY KEY REFERENCES budget_buys(order_seq),
micros INTEGER NOT NULL CHECK(micros>0)
);
CREATE TABLE IF NOT EXISTS budget_spend_micros (
order_seq INTEGER PRIMARY KEY REFERENCES budget_buys(order_seq),
micros INTEGER NOT NULL CHECK(micros>=0)
+46
View File
@@ -0,0 +1,46 @@
use exchange::Exchange;
use serde_json::json;
#[test]
fn exact_market_buy_budget_survives_fees_rejection_and_restart() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("precise.sqlite");
let mut db = Exchange::open(&path).unwrap();
for cmd in [
json!({"op":"fund","id":"buyer","account":"buyer","micros":5000}),
json!({"op":"fund","id":"seller","account":"seller","cents":200}),
json!({"op":"list","id":"list","market":"e","rules":"test","tick_size":"0.001","taker_fee_rate_ppm":50000}),
json!({"op":"split","id":"split","account":"seller","market":"e","qty":1}),
json!({"op":"open","id":"open","market":"e"}),
json!({"op":"order","id":"ask","account":"seller","market":"e","outcome":"YES","side":"sell","qty":1,"price_micros":13000}),
] {
db.execute(cmd).unwrap();
}
let estimate = db
.execute(json!({"op":"estimate","side":"buy","asset_id":"eb:YES:e","amount_micros":5000}))
.unwrap();
assert_eq!(estimate["filled_shares"], json!(0.36));
assert_eq!(estimate["order_amounts"]["makerAmount"], "5000");
assert_eq!(estimate["total_spent_micros"], 4910);
assert_eq!(estimate["unspent_micros"], 90);
let mut order = json!({"op":"market_buy","id":"buy","account":"buyer","asset_id":"eb:YES:e",
"amount_micros":5000,"max_price_micros":13000,"tif":"FOK"});
assert!(db.execute(order.clone()).is_err());
assert_eq!(db.wallet_balance_micros("buyer", None).unwrap(), 5000);
order["tif"] = json!("FAK");
let receipt = db.execute(order.clone()).unwrap();
assert_eq!(receipt["amount_cents"], json!(0.5));
assert_eq!(receipt["amount_micros"], 5000);
assert_eq!(receipt["total_spent_micros"], 4910);
assert_eq!(receipt["unspent_micros"], 90);
drop(db);
let mut db = Exchange::open(path).unwrap();
assert_eq!(db.execute(order).unwrap(), receipt);
let read = db
.execute(json!({"op":"open_orders","account":"buyer","order":receipt["order"]}))
.unwrap();
assert_eq!(read["orders"][0]["amount_cents"], json!(0.5));
assert_eq!(read["orders"][0]["amount_micros"], 5000);
assert_eq!(db.wallet_balance_micros("buyer", None).unwrap(), 90);
}
@@ -0,0 +1,35 @@
{
"order_config": {
"chain_id": 31337,
"tokens": [
{
"token_id": "123",
"asset_id": "eb:YES:demo",
"verifying_contract": "0x0000000000000000000000000000000000000001"
}
]
},
"wallet": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
"expected_order_hash": "0xb6d17dee5bf6e9a6459f086ca414744339d7f9a56e74a750c933f05a9e45cc15",
"request": {
"owner": "alice-key",
"orderType": "FAK",
"deferExec": false,
"postOnly": false,
"order": {
"salt": 43,
"maker": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
"signer": "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf",
"tokenId": "123",
"makerAmount": "5000",
"takerAmount": "384615",
"side": "BUY",
"signatureType": 0,
"timestamp": "1782753357000",
"expiration": "0",
"metadata": "0x0000000000000000000000000000000000000000000000000000000000000000",
"builder": "0x0000000000000000000000000000000000000000000000000000000000000000",
"signature": "0xa34d3219b0bce4f98945724cf5513cf845230727dbf9d55e9f3d6b4159396748029725bb2d0af91c9b8e7369b232ed69e599d8c97c501c405cef0be1e13954ce1c"
}
}
}
+6 -2
View File
@@ -280,10 +280,12 @@ 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/signed-ctf-micro-budget.json) 提交 5000 微美元的 FAK。在价格 0.013 美元、盘口至少有 1 份且费率为零时,成交 0.38 份、花费 4940 微美元、退回 60。开启 0.05 的费用系数后,同样预算最多成交 0.36 份,本金 4680、费用 230、退款 90。若改为 FOK 且预算无法用尽,本地回滚。历史回执继续按原请求读回。公开响应单位与官方一致,生产是否接受这一细预算及其最小成交单位仍待实测。[官方签名金额字段](https://docs.polymarket.com/api-reference/trade/post-a-new-order)
## 由对手盘口推导市价单保护价
省略最高买价或最低卖价时,使用当前交易品盘口的价格优先顺序。买单逐档累计金额,卖单逐档累计份额,首次达到请求量的一档给出保护价。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)
@@ -332,7 +334,7 @@ ERC‑1271 订单的 maker 和 signer 同为本地凭证绑定的合约钱包。
Protocol V2 的 position ID 继续通过订单 `tokenId` 字段传输。资产映射指定 EIP‑712 版本 `"3"` 和 Exchange 合约,配置校验结果索引以及本地市场内成对仓位的条件和合约一致性。对官方 Polygon 部署执行只读 `domainSeparator()`,得到 `0x466c63910185bbd55e8679264200c4e0abdcbb0c6264eb3d41d13326022e095b`,与按 SDK 的域名、版本 `3`、链 ID `137` 和代理合约地址独立计算的结果一致。合成样例用隔离的链 ID,覆盖四种钱包类型。[官方 SDK 订单路由](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/order_builder/builder.py) · [仓位 ID 规范](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/position-ids.md) · [签名样例](examples/signed-protocol-v2-orders.json)
限价单要求签名金额和本地盘口精度完全匹配。即时买单的保护价向下取整,卖单向上取整,两者仍须通过市场步长校验。市场买单沿用本地整分预算,份额限价单和即时卖单沿用 0.01 份的撮合单位。`POST /orders` 可一次提交 1 至 15 笔,按输入顺序逐项返回成功或失败。本地写事务逐项受理,生产接口并行处理。链上成交回执与 Protocol V2 的链上结算仍待接入。本轮未使用生产交易凭证。[官方批量接口](https://docs.polymarket.com/api-reference/trade/post-multiple-orders)
限价单要求签名金额和本地盘口精度完全匹配。即时买单的保护价向下取整,卖单向上取整,两者仍须通过市场步长校验。市场买单保留签名中的整数微美元预算,份额限价单和即时卖单沿用 0.01 份的撮合单位。`POST /orders` 可一次提交 1 至 15 笔,按输入顺序逐项返回成功或失败。本地写事务逐项受理,生产接口并行处理。链上成交回执与 Protocol V2 的链上结算仍待接入。本轮未使用生产交易凭证。[官方批量接口](https://docs.polymarket.com/api-reference/trade/post-multiple-orders)
订单提交回执采用 SDK 的 `makingAmount`、`takingAmount` 和 `tradeIDs`。无即时成交时采用官方挂单示例的签名金额。有即时成交时,回执按买卖方向返回实际成交本金及份额的整数微单位,费用保存在本地回执中。两档合计成交时返回每笔执行 ID,与账户成交查询一致。部分成交的剩余挂单继续显示在订单查询中。重试从原订单的吃单执行重建回执,后来作为挂单方的成交和集合竞价不计入首次提交。生产环境的延迟匹配状态、金额计算细节与链上回执仍待实测。[官方下单说明](https://docs.polymarket.com/trading/place-orders#check-the-response) · [官方 Rust SDK 回执](https://github.com/Polymarket/rs-clob-client-v2/blob/main/src/clob/types/response.rs)
@@ -340,6 +342,8 @@ Protocol V2 的 position ID 继续通过订单 `tokenId` 字段传输。资产
`itode` 市场使用同一持久化队列,短时等待固定为 150 毫秒。CLOB 的 `/clob-markets/{condition_id}` 在启用时发布 `itode: true`。HTTP 等待时释放 Exchange 互斥锁,按原订单哈希查询最终执行结果。批量响应只等待同步短时窗口并保留原顺序。重启、重试或更改市场延迟设置时,以订单首次入队的响应模式为准。生产抖动和批量尾延迟仍待实测。[官方撮合窗口](https://docs.polymarket.com/concepts/order-lifecycle)
单笔和批量接口都将省略的 `orderType` 视为 GTC。用同一签名分别提交省略字段和显式 GTC 的请求,两者关联同一个订单哈希。同步延迟期间对手撤单时,回放样例中的买单以每份 0.60 挂 3 份,返回 `live`、`makingAmount=1800000` 和 `takingAmount=3000000`。这是本地重新撮合后进入盘口的回执行为,生产环境这一竞态仍待实测。[官方单笔接口](https://docs.polymarket.com/api-reference/trade/post-a-new-order) · [官方批量接口](https://docs.polymarket.com/api-reference/trade/post-multiple-orders) · [签名样例](examples/signed-ctf-order.json)
## 市场 WebSocket 的订阅与推送
`/ws/market` 使用原始行情协议的毫秒时间戳字符串和顶层 `event_type`。首次 `type: market` 订阅默认收到一组 `book`;可用 `initial_dump: false` 跳过。动态 `subscribe` 总是为新资产发送快照,重复订阅同一资产保持原进度。退订只影响当前连接。两侧同时订阅时,变化可合并在同一条 `price_change` 内;已有订阅的积压变化和新订阅的快照使用各自起点。启用 `custom_feature_enabled` 后额外发送最优档发生变化的 `best_bid_ask`,同价档量变化只发 `price_change`。协议样例采用 Eventbook 资产 ID。[官方原始帧示例](https://docs.polymarket.com/market-data/realtime-data.md) · [可重放的客户端文本帧](examples/market-ws.txt)