Route orders and market data by stable outcome asset IDs
This commit is contained in:
@@ -9,6 +9,10 @@
|
||||
```mermaid
|
||||
flowchart LR
|
||||
test["tests/market.rs"] -->|通过公开 API 驱动市场| api["src/lib.rs"]
|
||||
api -->|解析结果资产 ID| assets["src/assets.rs"]
|
||||
queries -->|生成目录中的结果资产| assets
|
||||
acct -->|回传订单的资产 ID| assets
|
||||
portfolio -->|回传持仓的资产 ID| assets
|
||||
api -->|启动和请求时检查到期时间| expiry["src/expiry.rs"]
|
||||
expiry -->|释放订单剩余预留| book["src/book.rs"]
|
||||
api -->|初始化数据库| schema["src/schema.sql"]
|
||||
@@ -164,3 +168,20 @@ sequenceDiagram
|
||||
```
|
||||
|
||||
没有请求时,模拟 CLI 会等待输入。下一次查询、交易或进程重启会先结清已到期的余单。成交、手动撤单和停盘会同步移除相应的待到期项。
|
||||
|
||||
## 用结果资产 ID 下单
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as CLI
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
participant B as 常驻盘口
|
||||
C->>E: assets 按市场查询,或 catalog 按赛事查询
|
||||
E->>D: 读取已上架市场和结果标签
|
||||
E-->>C: 返回 YES 和 NO 各自的 asset_id
|
||||
C->>E: order 提交选中的 asset_id
|
||||
E->>D: 在订单事务中确认市场存在并核对请求字段
|
||||
E->>B: 使用相同的市场与结果定位原盘口
|
||||
E-->>C: 返回订单回执
|
||||
```
|
||||
|
||||
@@ -68,11 +68,15 @@ impl Filter {
|
||||
let quantity: i64 = row.get(5)?;
|
||||
let remaining: i64 = row.get(6)?;
|
||||
let status: String = row.get(7)?;
|
||||
orders.push(json!({"order":id,"market":row.get::<_,String>(1)?,
|
||||
"outcome":row.get::<_,String>(2)?,"side":row.get::<_,String>(3)?,
|
||||
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),
|
||||
"outcome":outcome,"side":row.get::<_,String>(3)?,
|
||||
"price_micros":row.get::<_,i64>(4)?*10000,"original_size":quantity,
|
||||
"size_matched":quantity-remaining,"open_size":if status=="live"{remaining}else{0},
|
||||
"status":status,"expiration":row.get::<_,Option<i64>>(8)?}));
|
||||
"status":status,"expiration":row.get::<_,Option<i64>>(8)?}),
|
||||
);
|
||||
last_id = Some(id);
|
||||
}
|
||||
Ok(json!({"orders":orders,"next_after":next_after}))
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
use crate::validation::identifier;
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::Connection;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
// The outcome precedes the market so every valid market string, including
|
||||
// those containing colons, round-trips without escaping or a database migration.
|
||||
pub(crate) fn id(market: &str, outcome: &str) -> String {
|
||||
format!("eb:{outcome}:{market}")
|
||||
}
|
||||
|
||||
pub(crate) fn outcomes(market: &str, yes: &str, no: &str) -> Value {
|
||||
json!([
|
||||
{"outcome":"YES","label":yes,"asset_id":id(market,"YES")},
|
||||
{"outcome":"NO","label":no,"asset_id":id(market,"NO")}
|
||||
])
|
||||
}
|
||||
|
||||
pub(crate) fn market_assets(db: &Connection, market: &str) -> Result<Value> {
|
||||
identifier(market)?;
|
||||
let (yes, no, phase): (String, String, String) = db.query_row(
|
||||
"SELECT COALESCE(s.yes_label,'YES'),COALESCE(s.no_label,'NO'),m.phase
|
||||
FROM markets m LEFT JOIN sports_markets s ON s.market=m.id WHERE m.id=?1",
|
||||
[market],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
Ok(json!({"market":market,"phase":phase,"outcomes":outcomes(market,&yes,&no)}))
|
||||
}
|
||||
|
||||
// Resolve only commands that address one outcome. Keep the original request
|
||||
// untouched in the idempotency ledger so historic receipts still replay exactly.
|
||||
pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
|
||||
if !matches!(
|
||||
request["op"].as_str(),
|
||||
Some("order" | "book" | "quote" | "history" | "open_orders")
|
||||
) {
|
||||
return Ok(());
|
||||
}
|
||||
let fields = request.as_object_mut().context("expected object")?;
|
||||
let Some(asset) = fields.remove("asset_id") else {
|
||||
return Ok(());
|
||||
};
|
||||
let (outcome, market) = asset
|
||||
.as_str()
|
||||
.and_then(|s| s.strip_prefix("eb:"))
|
||||
.and_then(|s| s.split_once(':'))
|
||||
.context("invalid Eventbook asset_id")?;
|
||||
ensure!(matches!(outcome, "YES" | "NO"), "invalid asset outcome");
|
||||
identifier(market)?;
|
||||
for (field, value) in [("market", market), ("outcome", outcome)] {
|
||||
if let Some(existing) = fields.get(field) {
|
||||
ensure!(
|
||||
existing.as_str() == Some(value),
|
||||
"asset_id conflicts with {field}"
|
||||
);
|
||||
}
|
||||
fields.insert(field.to_owned(), json!(value));
|
||||
}
|
||||
let listed: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)",
|
||||
[market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(listed, "unknown Eventbook asset_id");
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::validation::identifier;
|
||||
use crate::{assets, validation::identifier};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, Transaction};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -141,6 +141,9 @@ impl Listing {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub(crate) enum Query {
|
||||
Assets {
|
||||
market: String,
|
||||
},
|
||||
Positions(crate::portfolio::Filter),
|
||||
OpenOrders(crate::account_orders::Filter),
|
||||
Book {
|
||||
@@ -167,6 +170,7 @@ pub(crate) enum Query {
|
||||
impl Query {
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
match self {
|
||||
Self::Assets { market } => assets::market_assets(db, &market),
|
||||
Self::Positions(filter) => filter.read(db),
|
||||
Self::OpenOrders(filter) => filter.read(db),
|
||||
Self::Book { market, outcome } => {
|
||||
@@ -185,7 +189,9 @@ impl Query {
|
||||
let levels = if side == "buy" { &mut bids } else { &mut asks };
|
||||
levels.push(json!({"price_micros":price*10000,"size":size}));
|
||||
}
|
||||
Ok(json!({"market":market,"outcome":outcome,"phase":phase,"bids":bids,"asks":asks}))
|
||||
Ok(
|
||||
json!({"asset_id":assets::id(&market,&outcome),"market":market,"outcome":outcome,"phase":phase,"bids":bids,"asks":asks}),
|
||||
)
|
||||
}
|
||||
Self::Quote { market, outcome } => {
|
||||
let phase = market_phase(db, &market, &outcome)?;
|
||||
@@ -212,9 +218,11 @@ impl Query {
|
||||
("continuous", _, _, Some(p)) => (Some(p * 10000), Some("last_trade")),
|
||||
_ => (None, None),
|
||||
};
|
||||
Ok(json!({"market":market,"outcome":outcome,"phase":phase,
|
||||
Ok(
|
||||
json!({"asset_id":assets::id(&market,&outcome),"market":market,"outcome":outcome,"phase":phase,
|
||||
"best_bid_micros":bid.map(|p|p*10000),"best_ask_micros":ask.map(|p|p*10000),
|
||||
"last_trade_micros":last.map(|p|p*10000),"display_price_micros":display,"source":source}))
|
||||
"last_trade_micros":last.map(|p|p*10000),"display_price_micros":display,"source":source}),
|
||||
)
|
||||
}
|
||||
Self::Catalog { event } => {
|
||||
let detail = db.query_row(
|
||||
@@ -229,16 +237,21 @@ impl Query {
|
||||
let mut rows = stmt.query([event])?;
|
||||
let mut markets = Vec::new();
|
||||
while let Some(r) = rows.next()? {
|
||||
markets.push(json!({"market":r.get::<_,String>(0)?,
|
||||
let market: String = r.get(0)?;
|
||||
let yes: String = r.get(2)?;
|
||||
let no: String = r.get(3)?;
|
||||
markets.push(
|
||||
json!({"market":market, "outcomes":assets::outcomes(&market,&yes,&no),
|
||||
"question":r.get::<_,String>(1)?,
|
||||
"yes_label":r.get::<_,String>(2)?,
|
||||
"no_label":r.get::<_,String>(3)?,
|
||||
"yes_label":yes,
|
||||
"no_label":no,
|
||||
"terms":serde_json::from_str::<Value>(&r.get::<_,String>(4)?)?,
|
||||
"source":r.get::<_,String>(5)?,
|
||||
"resolver":r.get::<_,String>(6)?,
|
||||
"rules_version":r.get::<_,i64>(7)?,
|
||||
"rules":r.get::<_,String>(8)?,
|
||||
"phase":r.get::<_,String>(9)?}));
|
||||
"phase":r.get::<_,String>(9)?}),
|
||||
);
|
||||
}
|
||||
Ok(json!({"event":detail,
|
||||
"markets":markets}))
|
||||
@@ -271,8 +284,10 @@ impl Query {
|
||||
},
|
||||
)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(json!({"kind":"last_trade",
|
||||
"points":points}))
|
||||
Ok(
|
||||
json!({"kind":"last_trade","asset_id":assets::id(&market,&outcome),
|
||||
"points":points}),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
mod account_orders;
|
||||
mod assets;
|
||||
mod catalog;
|
||||
mod expiry;
|
||||
mod validation;
|
||||
@@ -35,10 +36,12 @@ impl Exchange {
|
||||
pub fn execute(&mut self, payload: Value) -> Result<Value> {
|
||||
if matches!(
|
||||
payload["op"].as_str(),
|
||||
Some("catalog" | "history" | "quote" | "book" | "open_orders" | "positions")
|
||||
Some("assets" | "catalog" | "history" | "quote" | "book" | "open_orders" | "positions")
|
||||
) {
|
||||
let query: catalog::Query = serde_json::from_value(payload)?;
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
||||
let mut request = payload;
|
||||
assets::resolve(&tx, &mut request)?;
|
||||
let query: catalog::Query = serde_json::from_value(request)?;
|
||||
let value = query.read(&tx)?;
|
||||
tx.commit()?;
|
||||
return Ok(value);
|
||||
@@ -98,6 +101,7 @@ impl Exchange {
|
||||
body.as_object_mut()
|
||||
.context("expected object")?
|
||||
.remove("id");
|
||||
assets::resolve(&tx, &mut body)?;
|
||||
let command = serde_json::from_value(body)?;
|
||||
let external = self.books.changes(&tx)?;
|
||||
self.books.apply(external);
|
||||
|
||||
@@ -56,7 +56,7 @@ impl Filter {
|
||||
let payout: Option<i64> = row.get(6)?;
|
||||
let pairs: i64 = row.get(7)?;
|
||||
positions.push(json!({
|
||||
"market":market, "outcome":outcome, "status":status, "size":size,
|
||||
"asset_id":crate::assets::id(&market,&outcome),"market":market, "outcome":outcome, "status":status, "size":size,
|
||||
"available_size":row.get::<_,i64>(3)?, "reserved_size":row.get::<_,i64>(4)?,
|
||||
"redeemable":status=="REDEEMABLE", "payout_cents":payout.map(|p|p*size),
|
||||
"mergeable":pairs>0, "available_pairs":row.get::<_,i64>(8)?
|
||||
|
||||
@@ -229,6 +229,14 @@ fn sports_catalog_and_trade_curve_survive_retries() {
|
||||
catalog = e.execute(serde_json::from_str(line).unwrap()).unwrap();
|
||||
}
|
||||
assert_eq!(catalog["markets"].as_array().unwrap().len(), 6);
|
||||
for market in catalog["markets"].as_array().unwrap() {
|
||||
let direct = e
|
||||
.execute(json!({"op":"assets","market":market["market"]}))
|
||||
.unwrap();
|
||||
assert_eq!(market["outcomes"], direct["outcomes"]);
|
||||
assert_eq!(market["outcomes"][0]["label"], market["yes_label"]);
|
||||
assert_eq!(market["outcomes"][1]["label"], market["no_label"]);
|
||||
}
|
||||
setup(&mut e);
|
||||
e.execute(order("ask", "alice", "sell", 50, 2)).unwrap();
|
||||
e.execute(order("bid", "bob", "buy", 50, 2)).unwrap();
|
||||
@@ -725,3 +733,61 @@ fn gtd_expiry_survives_rejection_and_recovery() {
|
||||
let mut e = Exchange::open(path).unwrap();
|
||||
assert_eq!(state(&mut e)["accounts"][1]["cash"], 1880);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asset_discovery_and_routing_share_one_orderbook_across_restart() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("assets.db");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
setup(&mut e);
|
||||
let market = "杯赛:NO:决赛";
|
||||
e.execute(json!({"op":"list","id":"new","market":market,"rules":"official"}))
|
||||
.unwrap();
|
||||
let discovery = json!({"op":"assets","market":market});
|
||||
let assets = e.execute(discovery.clone()).unwrap()["outcomes"].clone();
|
||||
let yes = assets[0]["asset_id"].clone();
|
||||
let no = assets[1]["asset_id"].clone();
|
||||
assert_ne!(yes, no);
|
||||
e.execute(json!({"op":"split","id":"pairs","account":"alice","market":market,"qty":3}))
|
||||
.unwrap();
|
||||
e.execute(json!({"op":"open","id":"open","market":market}))
|
||||
.unwrap();
|
||||
let ask = json!({"op":"order","id":"offer","asset_id":yes,"account":"alice","side":"sell","price":47,"qty":3});
|
||||
let receipt = e.execute(ask.clone()).unwrap();
|
||||
drop(e);
|
||||
let mut e = Exchange::open(path).unwrap();
|
||||
assert_eq!(e.execute(discovery).unwrap()["outcomes"], assets);
|
||||
assert_eq!(e.execute(ask).unwrap(), receipt);
|
||||
let book = e.execute(json!({"op":"book","asset_id":yes})).unwrap();
|
||||
assert_eq!(
|
||||
book,
|
||||
e.execute(json!({"op":"book","market":market,"outcome":"YES"}))
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(book["asks"][0]["size"], 3);
|
||||
let opposite = e.execute(json!({"op":"quote","asset_id":no})).unwrap();
|
||||
assert_eq!(opposite["best_bid_micros"], 530000);
|
||||
let mut buy = order("take", "bob", "buy", 47, 2);
|
||||
buy["market"] = json!(market);
|
||||
let mut conflicting = buy.clone();
|
||||
conflicting["asset_id"] = no.clone();
|
||||
assert!(e.execute(conflicting).is_err());
|
||||
assert_eq!(e.execute(buy).unwrap()["filled"], 2);
|
||||
let history = e
|
||||
.execute(json!({"op":"history","asset_id":yes,"from_ms":0,"to_ms":i64::MAX,"limit":10}))
|
||||
.unwrap();
|
||||
assert_eq!(history["points"][0]["quantity"], 2);
|
||||
assert_eq!(history["asset_id"], yes);
|
||||
let live = e
|
||||
.execute(json!({"op":"open_orders","asset_id":yes,"account":"alice"}))
|
||||
.unwrap();
|
||||
assert_eq!(live["orders"][0]["open_size"], 1);
|
||||
assert_eq!(live["orders"][0]["asset_id"], yes);
|
||||
let held = e
|
||||
.execute(json!({"op":"positions","market":market,"account":"bob"}))
|
||||
.unwrap();
|
||||
assert_eq!(held["positions"][0]["asset_id"], yes);
|
||||
for asset in ["eb:YES:unlisted", "eb:DRAW:e", "venue:123"] {
|
||||
assert!(e.execute(json!({"op":"book","asset_id":asset})).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user