市场成交与持仓数据及含吃单手续费的本地交割 #7
Generated
+1
@@ -82,6 +82,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"exchange",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
|
||||
@@ -11,3 +11,4 @@ serde.workspace = true
|
||||
tungstenite = "0.28"
|
||||
tiny_http = "0.12"
|
||||
serde_urlencoded = "0.7"
|
||||
percent-encoding = "2"
|
||||
|
||||
@@ -140,3 +140,21 @@ sequenceDiagram
|
||||
E-->>H: 每个资产的成交价和方向
|
||||
H-->>C: 单笔对象或含 token_id 的数组
|
||||
```
|
||||
|
||||
客户端可通过 `GET /tick-size?token_id=…` 或 `GET /tick-size/{token_id}` 读取当前报价步长。URL 路径中的空格编码为 %20,加号表示加号本身。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs"] -->|解码 token_id| T["exchange/tick_size.rs"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http
|
||||
participant E as Exchange
|
||||
C->>H: GET /tick-size 或 /tick-size/{token_id}
|
||||
H->>E: 根据结果资产查询当前已提交步长
|
||||
E-->>H: 精确十进制数或查无市场
|
||||
H-->>C: minimum_tick_size 或 404 错误
|
||||
```
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use anyhow::Result;
|
||||
use exchange::{Exchange, HistoryError, HistoryQuery};
|
||||
use percent_encoding::percent_decode_str;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::{io::Read, net::TcpListener, sync::Mutex, thread};
|
||||
@@ -88,6 +89,32 @@ fn last_prices(engine: &Mutex<Exchange>, tokens: Vec<String>, single: bool) -> R
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TokenQuery {
|
||||
token_id: String,
|
||||
}
|
||||
|
||||
fn tick_size(engine: &Mutex<Exchange>, params: &str, segment: Option<&str>) -> Reply {
|
||||
let invalid = (400, "Invalid token id");
|
||||
let token = match segment {
|
||||
Some(raw) => percent_decode_str(raw).decode_utf8().map_err(|_| invalid)?,
|
||||
None => serde_urlencoded::from_str::<TokenQuery>(params)
|
||||
.map_err(|_| invalid)?
|
||||
.token_id
|
||||
.into(),
|
||||
};
|
||||
let size = engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "Internal server error"))?
|
||||
.minimum_tick_size(&token)
|
||||
.map_err(|e| match e {
|
||||
exchange::MarketDataError::Invalid(_) => invalid,
|
||||
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
|
||||
})?
|
||||
.ok_or((404, "market not found"))?;
|
||||
Ok(json!({"minimum_tick_size":size}))
|
||||
}
|
||||
|
||||
fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
let (path, params) = req.url().split_once('?').unwrap_or((req.url(), ""));
|
||||
let mut allow = None;
|
||||
@@ -95,7 +122,16 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
let (status, body) = history(params, engine);
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
let tick_segment = path
|
||||
.strip_prefix("/tick-size/")
|
||||
.filter(|s| !s.contains('/'));
|
||||
let is_tick_route = path == "/tick-size" || tick_segment.is_some();
|
||||
let reply = match (req.method(), path) {
|
||||
(&Method::Get, _) if is_tick_route => tick_size(engine, params, tick_segment),
|
||||
(_, _) if is_tick_route => {
|
||||
allow = Some("GET");
|
||||
Err((405, "Method not allowed"))
|
||||
}
|
||||
(&Method::Get, "/book") => serde_urlencoded::from_str::<BookParam>(params)
|
||||
.map_err(|_| (400, "Invalid token id"))
|
||||
.and_then(|p| query(engine, vec![p], true)),
|
||||
@@ -202,6 +238,7 @@ mod tests {
|
||||
json!({"op":"list","id":"list","market":market,"rules":"simulated","tick_size":"0.01"}),
|
||||
)
|
||||
.unwrap();
|
||||
db.execute(json!({"op":"list","id":"path-market","market":"map+2/1","rules":"simulation","tick_size":"0.0025"})).unwrap();
|
||||
let yes = format!("eb:YES:{market}");
|
||||
let no = format!("eb:NO:{market}");
|
||||
let expected_yes = db
|
||||
@@ -223,7 +260,17 @@ mod tests {
|
||||
let csv = serde_urlencoded::to_string([("token_ids", format!("{yes},{no}"))]).unwrap();
|
||||
let last_batch = format!("/last-trades-prices?{csv}");
|
||||
let last_single = encoded.replacen("/book?", "/last-trade-price?", 1);
|
||||
let tick_query = encoded.replacen("/book?", "/tick-size?", 1);
|
||||
let cases = [
|
||||
("GET",tick_query.as_str(),String::new(),200,Some(json!({"minimum_tick_size":0.01}))),
|
||||
("GET","/tick-size/eb%3ANO%3Amap%202%3A%E8%83%9C%E8%80%85",String::new(),200,Some(json!({"minimum_tick_size":0.01}))),
|
||||
("GET","/tick-size/eb:YES:map+2%2F1",String::new(),200,Some(json!({"minimum_tick_size":0.0025}))),
|
||||
("GET","/tick-size?token_id=eb%3AYES%3Amap%2B2%2F1",String::new(),200,Some(json!({"minimum_tick_size":0.0025}))),
|
||||
("GET","/tick-size/eb:YES:missing",String::new(),404,Some(json!({"error":"market not found"}))),
|
||||
("GET","/tick-size/",String::new(),400,Some(json!({"error":"Invalid token id"}))),
|
||||
("GET","/tick-size/eb:YES:%FF",String::new(),400,Some(json!({"error":"Invalid token id"}))),
|
||||
("GET","/tick-size",String::new(),400,Some(json!({"error":"Invalid token id"}))),
|
||||
("POST","/tick-size/eb:YES:e",String::new(),405,None),
|
||||
("GET",last_single.as_str(),String::new(),200,Some(no_fills)),
|
||||
("GET",last_batch.as_str(),String::new(),200,Some(batch_no_fills.clone())),
|
||||
("POST","/last-trades-prices",json!([{"token_id":yes,"side":"SELL"},{"token_id":no}]).to_string(),200,Some(batch_no_fills)),
|
||||
|
||||
@@ -1026,3 +1026,26 @@ sequenceDiagram
|
||||
L->>L: 对互补结果反转方向;缺少吃单记录时方向留空
|
||||
L-->>H: 按输入顺序返回,保留重复项
|
||||
```
|
||||
|
||||
### 已提交的报价步长
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["cli/market_http.rs"] --> T["tick_size.rs"]
|
||||
S["book_snapshot.rs"] -->|使用相同的旧盘默认步长| T
|
||||
T --> I["inventory.rs 的定点数转换"]
|
||||
T --> A["assets.rs 的结果标识解析"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant W as 调价命令
|
||||
participant D as SQLite
|
||||
participant Q as 步长查询
|
||||
W->>D: 在写事务内调整步长和受影响的挂单
|
||||
Q->>D: 联结市场与配置读取步长
|
||||
D-->>Q: 写事务提交前返回旧步长
|
||||
W->>D: 提交
|
||||
Q->>D: 按 YES 或 NO 重新查询同一市场
|
||||
D-->>Q: 返回新步长
|
||||
```
|
||||
|
||||
@@ -92,8 +92,8 @@ fn find(
|
||||
.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()),
|
||||
.unwrap_or(TickSize::WHOLE_CENT)
|
||||
.text(),
|
||||
neg_risk,
|
||||
last_trade_price: Quote::current(tx, market, outcome)?
|
||||
.last
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{assets, minimum_size::MinimumSize};
|
||||
use crate::{assets, inventory, minimum_size::MinimumSize, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction};
|
||||
use serde::Deserialize;
|
||||
@@ -35,7 +35,31 @@ pub(crate) fn validate(tick: Option<&TickSize>, price: i64) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Exchange {
|
||||
/// Current grid for a listed local outcome, including the whole-cent legacy grid.
|
||||
pub fn minimum_tick_size(
|
||||
&self,
|
||||
token: &str,
|
||||
) -> Result<Option<serde_json::Number>, MarketDataError> {
|
||||
let (_, market) = assets::parse_id(token)
|
||||
.map_err(|_| MarketDataError::Invalid("Invalid token id".into()))?;
|
||||
let mut stmt = self.db.prepare_cached(
|
||||
"SELECT s.step_micros FROM markets m LEFT JOIN market_tick_sizes s ON s.market=m.id WHERE m.id=?1"
|
||||
)?;
|
||||
let tick = stmt
|
||||
.query_row([market], |r| r.get::<_, Option<i64>>(0))
|
||||
.optional()?;
|
||||
Ok(tick.map(|step| step.map(TickSize).unwrap_or(TickSize::WHOLE_CENT).number()))
|
||||
}
|
||||
}
|
||||
|
||||
impl TickSize {
|
||||
pub(crate) const WHOLE_CENT: Self = Self(10_000);
|
||||
|
||||
fn number(&self) -> serde_json::Number {
|
||||
inventory::decimal(self.0.into(), inventory::UNIT)
|
||||
}
|
||||
|
||||
pub(crate) fn parse(value: &str) -> Result<Self> {
|
||||
let micros = match value.trim_end_matches('0') {
|
||||
"0.1" => 100_000,
|
||||
@@ -66,7 +90,7 @@ impl TickSize {
|
||||
}
|
||||
|
||||
pub fn text(&self) -> String {
|
||||
format!("0.{:06}", self.0).trim_end_matches('0').to_owned()
|
||||
self.number().to_string()
|
||||
}
|
||||
|
||||
pub fn check(&self, price: i64) -> Result<()> {
|
||||
|
||||
@@ -2285,6 +2285,14 @@ fn configured_ticks_bind_order_amounts_execution_and_opening_price() {
|
||||
e.execute(json!({"op":"list","id":"invalid","market":"legacy","rules":"r"}))
|
||||
.unwrap();
|
||||
assert!(e.execute(json!({"op":"assets","market":"legacy"})).unwrap()["tick_size"].is_null());
|
||||
assert_eq!(
|
||||
json!(e.minimum_tick_size("eb:NO:legacy").unwrap()),
|
||||
json!(0.01)
|
||||
);
|
||||
assert!(e
|
||||
.minimum_tick_size("eb:YES:no-such-market")
|
||||
.unwrap()
|
||||
.is_none());
|
||||
e.execute(json!({"op":"order","id":"old","market":"legacy","outcome":"YES","account":"bob","side":"buy","price":0,"qty":1})).unwrap();
|
||||
}
|
||||
|
||||
@@ -2293,11 +2301,18 @@ fn replayed_tick_changes_preserve_valid_orders_and_release_only_residuals() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("tick-changes.db");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
let reader = Exchange::open(&path).unwrap();
|
||||
let mut original = Value::Null;
|
||||
let mut cursor = Value::Null;
|
||||
for line in include_str!("../../../docs/examples/tick-changes.jsonl").lines() {
|
||||
let cmd: Value = serde_json::from_str(line).unwrap();
|
||||
let response = e.execute(cmd.clone()).unwrap();
|
||||
if let Some(step) = cmd.get("new_tick_size").or(cmd.get("tick_size")) {
|
||||
for token in ["eb:YES:cup", "eb:NO:cup"] {
|
||||
let current = reader.minimum_tick_size(token).unwrap().unwrap();
|
||||
assert_eq!(current.to_string(), step.as_str().unwrap());
|
||||
}
|
||||
}
|
||||
match cmd["op"].as_str().unwrap() {
|
||||
"tick_size_change" if cmd["id"] == "finer" => {
|
||||
assert_eq!(response["canceled"], json!([]))
|
||||
@@ -2325,6 +2340,10 @@ fn replayed_tick_changes_preserve_valid_orders_and_release_only_residuals() {
|
||||
}
|
||||
drop(e);
|
||||
let mut e = Exchange::open(path).unwrap();
|
||||
assert_eq!(
|
||||
json!(e.minimum_tick_size("eb:YES:cup").unwrap()),
|
||||
json!(0.1)
|
||||
);
|
||||
let before = state(&mut e);
|
||||
let position = before["positions"]
|
||||
.as_array()
|
||||
|
||||
@@ -27,3 +27,9 @@ POST http://127.0.0.1:9002/last-trades-prices
|
||||
Content-Type: application/json
|
||||
|
||||
[{"token_id":"eb:YES:demo"},{"token_id":"eb:NO:demo"}]
|
||||
|
||||
### Fetch the active price increment by outcome ID
|
||||
GET http://127.0.0.1:9002/tick-size?token_id=eb%3AYES%3Ademo
|
||||
|
||||
### Fetch the same market grid with the other outcome in the path
|
||||
GET http://127.0.0.1:9002/tick-size/eb%3ANO%3Ademo
|
||||
|
||||
@@ -339,3 +339,9 @@ order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可
|
||||
Polymarket 的单资产最近成交接口规定,无成交时返回价格字符串 `"0.5"` 和空方向。Eventbook 的单笔与批量接口采用这个初值。挂单改变盘口时,这个值一直维持到首笔成交。以仓库的行情流样例为例:一张 0.40 的 YES 卖单挂出时仍返回 0.5;随后以 0.40 买入成交,返回 0.4、BUY。在 NO 上挂买单也不会改变 YES 的最近成交价。之后互补成交在 YES 返回 0.35、BUY,在 NO 返回 0.65、SELL。集合竞价和缺少吃单记录的旧成交保留实价、方向留空。批量请求的无成交初值、重复项顺序以及互补成交的外场方向仍待生产样本验证。[单资产最近成交价](https://docs.polymarket.com/api-reference/market-data/get-last-trade-price) · [批量接口](https://docs.polymarket.com/api-reference/market-data/get-last-trade-prices-request-body) · [行情流样例](examples/market-stream-trades.jsonl)
|
||||
|
||||
已知两侧报价可以推导中点,历史接口中每个点的采样规则另待验证。SDK 仓库也有针对 CLOB 历史价格字段 p 的公开提问;本地 V2 曲线当前由成交与模拟兑付生成。[关于历史点定义的问题](https://github.com/Polymarket/py-clob-client-v2/issues/106)
|
||||
|
||||
## 下单前的步长查询
|
||||
|
||||
同一市场的两个结果使用同一套报价步长。HTTP 参数和路径两种读法都返回数值字段 minimum_tick_size;旧市场未登记显式步长时使用本地既有的一美分报价单位。路径和查询参数均支持转义后的资产 ID。按本地标识格式解析失败返回 400,合法本地标识对应的市场不存在返回 404。[查询参数接口](https://docs.polymarket.com/api-reference/market-data/get-tick-size) · [路径参数接口](https://docs.polymarket.com/api-reference/market-data/get-tick-size-by-path-parameter)
|
||||
|
||||
固定版本的 Python SDK 在全新客户端且资产尚无已知 condition 映射时,以查询参数发起 GET,接着将返回值转成字符串并缓存在客户端。缓存命中时重复调用不会发起 HTTP 请求。若客户端已取得 condition 映射,它还有一条读取 CLOB 市场详情的路径。本文样例验证查询端点及本地已提交的调价;生产端自动切换的触发时点和 SDK 其他交易参数路径仍需单独对照。[SDK 实现](https://github.com/Polymarket/py-clob-client-v2/blob/9c7c9e89cbbc11528daae90dc66ef65c9380cbdf/py_clob_client_v2/client.py) · [调价样例](examples/tick-changes.jsonl)
|
||||
|
||||
Reference in New Issue
Block a user