Expose the current committed tick size by outcome ID

This commit is contained in:
2026-12-03 09:32:49 +08:00
parent b523a8890f
commit 81595a89ee
10 changed files with 149 additions and 4 deletions
+1
View File
@@ -11,3 +11,4 @@ serde.workspace = true
tungstenite = "0.28"
tiny_http = "0.12"
serde_urlencoded = "0.7"
percent-encoding = "2"
+18
View File
@@ -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 错误
```
+47
View File
@@ -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)),
+23
View File
@@ -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: 返回新步长
```
+2 -2
View File
@@ -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
+26 -2
View File
@@ -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<()> {
+19
View File
@@ -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()