市场成交与持仓数据及含吃单手续费的本地交割 #7
Generated
+66
@@ -27,6 +27,15 @@ version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
@@ -58,6 +67,35 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.15"
|
||||
@@ -77,6 +115,7 @@ dependencies = [
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha1",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
@@ -104,6 +143,16 @@ version = "0.1.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
@@ -296,6 +345,17 @@ dependencies = [
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
@@ -343,6 +403,12 @@ dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
|
||||
@@ -9,6 +9,7 @@ anyhow.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json = { workspace = true, features = ["arbitrary_precision"] }
|
||||
rusqlite.workspace = true
|
||||
sha1 = "0.10"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
@@ -876,3 +876,28 @@ sequenceDiagram
|
||||
E->>B: 用预算和保护价计算可成交数量
|
||||
E-->>C: 估价返回预期成交,下单提交成功后返回实际成交
|
||||
```
|
||||
|
||||
### 客户端读取订单簿快照
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
entry["lib.rs"] --> catalog["catalog.rs"]
|
||||
entry --> schema["book_snapshot_schema.sql"]
|
||||
catalog --> snapshot["book_snapshot.rs"]
|
||||
snapshot --> resident["resident.rs / matching"]
|
||||
snapshot --> metadata["minimum_size.rs / tick_size.rs / quotes.rs"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
participant B as 常驻盘口
|
||||
C->>E: clob_book(token_id)
|
||||
E->>D: 同一读事务内读取变更、市场规格、时间和最近成交
|
||||
E->>B: 应用已提交的订单增量,读取两边的聚合档位
|
||||
B-->>E: 返回每档价格和总份额
|
||||
E->>E: 转为协议字符串,最优档排最后,计算快照哈希
|
||||
E-->>C: 快照、时间戳及 hash
|
||||
```
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
use crate::{
|
||||
assets,
|
||||
inventory::decimal,
|
||||
lots,
|
||||
minimum_size::MinimumSize,
|
||||
quotes::Quote,
|
||||
resident::Books,
|
||||
tick_size::{TickSize, PAR},
|
||||
};
|
||||
use anyhow::Result;
|
||||
use matching::Side;
|
||||
use rusqlite::Transaction;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use sha1::{Digest, Sha1};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Level {
|
||||
price: String,
|
||||
size: String,
|
||||
}
|
||||
|
||||
// Field order is part of the official SDK's SHA-1 preimage.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Snapshot {
|
||||
market: String,
|
||||
asset_id: String,
|
||||
timestamp: String,
|
||||
hash: String,
|
||||
bids: Vec<Level>,
|
||||
asks: Vec<Level>,
|
||||
min_order_size: String,
|
||||
tick_size: String,
|
||||
neg_risk: bool,
|
||||
last_trade_price: String,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
fn set_hash(&mut self) -> Result<()> {
|
||||
self.hash.clear();
|
||||
self.hash = format!("{:x}", Sha1::digest(serde_json::to_vec(self)?));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn read(tx: &Transaction, books: &mut Books, token: &str) -> Result<Value> {
|
||||
let (outcome, market) = assets::parse_id(token)?;
|
||||
let (at_ms, neg_risk): (i64, bool) = tx.query_row(
|
||||
"SELECT at_ms,EXISTS(SELECT 1 FROM neg_risk_members WHERE market=?1)
|
||||
FROM book_snapshot_times WHERE market=?1",
|
||||
[market],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
let changes = books.changes(tx)?;
|
||||
books.apply(changes);
|
||||
let book = books.get(market, outcome);
|
||||
let levels = |taker| {
|
||||
let mut result = Vec::new();
|
||||
if let Some(book) = book {
|
||||
for (price, size) in book.opposing_levels(taker) {
|
||||
result.push(Level {
|
||||
price: decimal(price.into(), PAR).to_string(),
|
||||
size: decimal(size, lots::PER_SHARE).to_string(),
|
||||
});
|
||||
}
|
||||
result.reverse(); // The reference client walks from the end of each side.
|
||||
}
|
||||
result
|
||||
};
|
||||
let mut snapshot = Snapshot {
|
||||
market: market.into(),
|
||||
asset_id: token.into(),
|
||||
timestamp: at_ms.to_string(),
|
||||
hash: String::new(),
|
||||
bids: levels(Side::Sell),
|
||||
asks: levels(Side::Buy),
|
||||
min_order_size: MinimumSize::load(tx, market)?
|
||||
.map(|s| s.text())
|
||||
.unwrap_or_else(|| "0.01".into()),
|
||||
tick_size: TickSize::load(tx, market)?
|
||||
.map(|s| s.text())
|
||||
.unwrap_or_else(|| "0.01".into()),
|
||||
neg_risk,
|
||||
last_trade_price: Quote::current(tx, market, outcome)?
|
||||
.last
|
||||
.map(|p| decimal(p.into(), PAR).to_string())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
snapshot.set_hash()?;
|
||||
Ok(serde_json::to_value(snapshot)?)
|
||||
}
|
||||
|
||||
pub(crate) fn local_levels(books: &Books, market: &str, outcome: &str, taker: Side) -> Vec<Value> {
|
||||
let Some(book) = books.get(market, outcome) else {
|
||||
return Vec::new();
|
||||
};
|
||||
book.opposing_levels(taker)
|
||||
.map(|(price, size)| {
|
||||
json!({
|
||||
"price_micros": price * crate::tick_size::PRICE_MICROS,
|
||||
"size": decimal(size, lots::PER_SHARE),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn reproduces_pinned_python_sdk_hash_vector() {
|
||||
let mut sample: Snapshot = serde_json::from_value(json!({
|
||||
"market":"0xaabbcc","asset_id":"100","timestamp":"123456789","hash":"prior",
|
||||
"bids":[{"price":"0.3","size":"100"},{"price":"0.4","size":"100"}],
|
||||
"asks":[{"price":"0.6","size":"100"},{"price":"0.7","size":"100"}],
|
||||
"min_order_size":"100","tick_size":"0.01","neg_risk":false,"last_trade_price":"0.5"
|
||||
}))
|
||||
.unwrap();
|
||||
sample.set_hash().unwrap();
|
||||
assert_eq!(sample.hash, "0458ea5755c9f73d64a14636fa5c36ed460ec394");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS book_snapshot_times (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id), at_ms INTEGER NOT NULL
|
||||
);
|
||||
-- History before this schema has no reliable timestamp for a depth-only edit.
|
||||
INSERT OR IGNORE INTO book_snapshot_times SELECT id,CAST(unixepoch('subsec')*1000 AS INTEGER) FROM markets;
|
||||
CREATE TRIGGER IF NOT EXISTS snapshot_listed AFTER INSERT ON markets BEGIN
|
||||
INSERT INTO book_snapshot_times VALUES(NEW.id,CAST(unixepoch('subsec')*1000 AS INTEGER));
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS snapshot_order_added AFTER INSERT ON orders
|
||||
WHEN NEW.status='live' AND NEW.remaining>0 BEGIN
|
||||
UPDATE book_snapshot_times SET at_ms=MAX(at_ms,CAST(unixepoch('subsec')*1000 AS INTEGER)) WHERE market=NEW.market;
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS snapshot_order_changed AFTER UPDATE OF status,remaining ON orders
|
||||
WHEN (NEW.status='live' OR OLD.status='live') AND (OLD.remaining<>NEW.remaining OR OLD.status<>NEW.status) BEGIN
|
||||
UPDATE book_snapshot_times SET at_ms=MAX(at_ms,CAST(unixepoch('subsec')*1000 AS INTEGER)) WHERE market=NEW.market;
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS snapshot_grid_changed AFTER INSERT ON tick_changes BEGIN
|
||||
UPDATE book_snapshot_times SET at_ms=MAX(at_ms,CAST(unixepoch('subsec')*1000 AS INTEGER)) WHERE market=NEW.market;
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS snapshot_group_joined AFTER INSERT ON neg_risk_members BEGIN
|
||||
UPDATE book_snapshot_times SET at_ms=MAX(at_ms,CAST(unixepoch('subsec')*1000 AS INTEGER)) WHERE market=NEW.market;
|
||||
END;
|
||||
COMMIT;
|
||||
@@ -267,6 +267,9 @@ pub(crate) enum Query {
|
||||
OpenOrders(crate::account_orders::Filter),
|
||||
Trades(crate::account_trades::Filter),
|
||||
PublicTrades(crate::public_trades::Request),
|
||||
ClobBook {
|
||||
token_id: String,
|
||||
},
|
||||
Book {
|
||||
market: String,
|
||||
outcome: String,
|
||||
@@ -322,23 +325,23 @@ impl Query {
|
||||
Self::PublicTrades(request) => request.read(db),
|
||||
Self::Trades(filter) => filter.read(db),
|
||||
Self::OpenOrders(filter) => filter.read(db),
|
||||
Self::ClobBook { token_id } => crate::book_snapshot::read(db, books, &token_id),
|
||||
Self::Book { market, outcome } => {
|
||||
let phase = market_phase(db, &market, &outcome)?;
|
||||
let mut stmt = db.prepare(
|
||||
"SELECT side,price,SUM(remaining) FROM visible_orders WHERE market=?1 AND outcome=?2
|
||||
GROUP BY side,price ORDER BY side, CASE side WHEN 'buy' THEN -price ELSE price END",
|
||||
)?;
|
||||
let mut rows = stmt.query(params![market, outcome])?;
|
||||
let mut bids = Vec::new();
|
||||
let mut asks = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
let side: String = row.get(0)?;
|
||||
let price: i64 = row.get(1)?;
|
||||
let size: i64 = row.get(2)?;
|
||||
let levels = if side == "buy" { &mut bids } else { &mut asks };
|
||||
levels
|
||||
.push(json!({"price_micros":price*100,"size":crate::lots::display(size)}));
|
||||
}
|
||||
let changes = books.changes(db)?;
|
||||
books.apply(changes);
|
||||
let bids = crate::book_snapshot::local_levels(
|
||||
books,
|
||||
&market,
|
||||
&outcome,
|
||||
matching::Side::Sell,
|
||||
);
|
||||
let asks = crate::book_snapshot::local_levels(
|
||||
books,
|
||||
&market,
|
||||
&outcome,
|
||||
matching::Side::Buy,
|
||||
);
|
||||
let minimum =
|
||||
crate::minimum_size::MinimumSize::load(db, &market)?.map(|size| size.text());
|
||||
Ok(
|
||||
|
||||
@@ -14,6 +14,7 @@ mod validation;
|
||||
mod volume;
|
||||
use validation::identifier;
|
||||
mod book;
|
||||
mod book_snapshot;
|
||||
mod cancellation;
|
||||
mod command;
|
||||
mod inventory;
|
||||
@@ -80,6 +81,11 @@ impl Exchange {
|
||||
db.execute_batch(include_str!("valuation_schema.sql"))?;
|
||||
}
|
||||
lots::migrate(&mut db)?;
|
||||
let snapshot_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='book_snapshot_times')", [], |r| r.get(0))?;
|
||||
if !snapshot_ready {
|
||||
db.execute_batch(include_str!("book_snapshot_schema.sql"))?;
|
||||
}
|
||||
let tx = expiry::transaction(&db, TransactionBehavior::Deferred)?;
|
||||
let books = Books::recover(&tx)?;
|
||||
tx.commit()?;
|
||||
@@ -124,6 +130,7 @@ impl Exchange {
|
||||
| "prices"
|
||||
| "quote_history"
|
||||
| "volume"
|
||||
| "clob_book"
|
||||
| "book"
|
||||
| "open_orders"
|
||||
| "positions"
|
||||
|
||||
@@ -2745,3 +2745,51 @@ fn automatic_price_uses_sdk_level_precision_while_cash_execution_is_exact() {
|
||||
assert_eq!(r["spent_cents"], 80);
|
||||
assert_eq!(r["filled"], 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sdk_book_groups_opposite_outcomes_and_preserves_snapshot_through_restart() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("snapshot.db");
|
||||
let mut writer = Exchange::open(&path).unwrap();
|
||||
let mut reader = Exchange::open(&path).unwrap();
|
||||
let mut snapshots = Vec::new();
|
||||
for line in include_str!("../../../docs/examples/clob-book.jsonl").lines() {
|
||||
let cmd: Value = serde_json::from_str(line).unwrap();
|
||||
if cmd["op"] == "clob_book" {
|
||||
snapshots.push(reader.execute(cmd).unwrap());
|
||||
} else {
|
||||
writer.execute(cmd).unwrap();
|
||||
}
|
||||
}
|
||||
let snapshot = &snapshots[1];
|
||||
assert_eq!(snapshots[0]["bids"], json!([]));
|
||||
assert_ne!(snapshots[0]["hash"], snapshot["hash"]);
|
||||
assert_eq!(snapshot["last_trade_price"], "");
|
||||
assert_eq!(snapshot["min_order_size"], "1");
|
||||
assert_eq!(snapshot["tick_size"], "0.01");
|
||||
assert_eq!(snapshot["neg_risk"], false);
|
||||
assert_eq!(
|
||||
snapshot["bids"],
|
||||
json!([{"price":"0.2","size":"1"},{"price":"0.3","size":"3.5"}])
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot["asks"],
|
||||
json!([{"price":"0.8","size":"2"},{"price":"0.6","size":"1"}])
|
||||
);
|
||||
drop(reader);
|
||||
let mut reader = Exchange::open(&path).unwrap();
|
||||
let request = json!({"op":"clob_book","token_id":"eb:YES:demo"});
|
||||
assert_eq!(&reader.execute(request.clone()).unwrap(), snapshot);
|
||||
let local = reader
|
||||
.execute(json!({"op":"book","asset_id":"eb:YES:demo"}))
|
||||
.unwrap();
|
||||
assert_eq!(local["bids"][0], json!({"price_micros":300000,"size":3.5}));
|
||||
writer
|
||||
.execute(json!({"op":"fund","id":"buyer","account":"buyer","cents":100}))
|
||||
.unwrap();
|
||||
writer.execute(json!({"op":"market_buy","id":"take","account":"buyer","asset_id":"eb:YES:demo","amount_cents":60})).unwrap();
|
||||
let changed = reader.execute(request).unwrap();
|
||||
assert_ne!(changed["hash"], snapshot["hash"]);
|
||||
assert_eq!(changed["last_trade_price"], "0.6");
|
||||
assert_eq!(changed["asks"], json!([{"price":"0.8","size":"2"}]));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
{"op":"list","id":"list","market":"demo","rules":"Local binary outcome","tick_size":"0.01","min_order_size":"1"}
|
||||
{"op":"fund","id":"fund","account":"maker","cents":3000}
|
||||
{"op":"split","id":"split","account":"maker","market":"demo","qty":10}
|
||||
{"op":"open","id":"open","market":"demo"}
|
||||
{"op":"clob_book","token_id":"eb:YES:demo"}
|
||||
{"op":"order","id":"direct","account":"maker","asset_id":"eb:YES:demo","side":"buy","price":30,"size_micros":2500000}
|
||||
{"op":"order","id":"reflected","account":"maker","asset_id":"eb:NO:demo","side":"sell","price":70,"qty":1}
|
||||
{"op":"order","id":"far","account":"maker","asset_id":"eb:YES:demo","side":"buy","price":20,"qty":1}
|
||||
{"op":"order","id":"near-ask","account":"maker","asset_id":"eb:YES:demo","side":"sell","price":60,"qty":1}
|
||||
{"op":"order","id":"far-ask","account":"maker","asset_id":"eb:YES:demo","side":"sell","price":80,"qty":2}
|
||||
{"op":"clob_book","token_id":"eb:YES:demo"}
|
||||
@@ -287,3 +287,9 @@ order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可
|
||||
[本地回放样例](examples/depth-protection.jsonl)包含普通 YES 卖单和 NO 买单映射出的 YES 卖盘。定价使用费用前的订单簿深度,实际成交另行检查预算、费用和本地数量精度。保护价只对该次读取的盘口有效,提交请求时会重新读取。客户端可显式提交预览过的保护价。相同请求号的重试返回已保存的原始回执。
|
||||
|
||||
在固定版本的官方 Python 函数上实测,若依次有 0.10、0.70、0.90 美元各一份卖盘,0.80 美元预算会得到 0.90 美元保护价。原因是前两档的二进制浮点和略低于 0.80。本地在推导委托保护价时复现这一可观察结果,成交和扣款仍按整数计算,两份合计恰好 0.80 美元。样例未向生产环境发单。
|
||||
|
||||
## CLOB 订单簿快照
|
||||
|
||||
通过 `{"op":"clob_book","token_id":"eb:YES:demo"}` 读取指定结果。买卖两边均把最优档放在数组末端,每档汇总同一价格的直接订单和互补结果映射出的流动性。价格以美元表示,份额以份表示,均保留为十进制字符串。最近成交为空时返回空串。哈希按固定字段顺序序列化、清空 hash 字段,再计算 SHA-1。官方测试数据的预期哈希为 `0458ea5755c9f73d64a14636fa5c36ed460ec394`。[SDK 解析与哈希实现](https://github.com/Polymarket/py-clob-client-v2/blob/9c7c9e89cbbc11528daae90dc66ef65c9380cbdf/py_clob_client_v2/utilities.py) · [官方测试向量](https://github.com/Polymarket/py-clob-client-v2/blob/9c7c9e89cbbc11528daae90dc66ef65c9380cbdf/tests/test_utilities.py)
|
||||
|
||||
[回放样例](examples/clob-book.jsonl)中,两张挂单在 0.30 美元档合计 3.5 份。市场和资产 ID 沿用 Eventbook 的本地标识。未设置专门交易规格时,返回本地默认最小限价委托 0.01 份、价格步长 0.01 美元。时间戳取本地盘口最近一次相关写入的毫秒时间;升级旧库以首次迁移时间为起点。现有 `book` 接口仍按最优价优先、整数微美元返回。线上时间戳刷新策略及 Protocol V2 扩展字段仍需实际盘口核对。
|
||||
|
||||
Reference in New Issue
Block a user