Serve last execution prices and directions for individual and batch token queries

This commit is contained in:
2026-12-03 09:25:44 +08:00
parent 9b25fdc424
commit b523a8890f
11 changed files with 220 additions and 16 deletions
+18
View File
@@ -122,3 +122,21 @@ sequenceDiagram
H->>E: 读取该窗口下一页
E-->>C: 后续点及是否还有数据
```
行情客户端也可以调用 `GET /last-trade-price`、`GET /last-trades-prices` 和 `POST /last-trades-prices`。GET 批量参数 token_ids 用逗号分隔;本地资产 ID 自身包含逗号时可使用 POST 的 JSON 数组。
```mermaid
flowchart LR
H["market_http.rs"] -->|"token_id 或资产列表"| L["exchange/last_trades.rs"]
```
```mermaid
sequenceDiagram
participant C as 客户端
participant H as market_http
participant E as Exchange
C->>H: 查询一个或多个资产的最后一笔成交
H->>E: last_trade_prices
E-->>H: 每个资产的成交价和方向
H-->>C: 单笔对象或含 token_id 的数组
```
+62 -5
View File
@@ -50,7 +50,7 @@ fn query(engine: &Mutex<Exchange>, params: Vec<BookParam>, single: bool) -> Repl
}
}
fn batch(req: &mut Request, engine: &Mutex<Exchange>) -> Reply {
fn batch_params(req: &mut Request) -> std::result::Result<Vec<BookParam>, (u16, &'static str)> {
if req.body_length().is_some_and(|n| n as u64 > MAX_BODY) {
return Err((413, "Request body too large"));
}
@@ -62,8 +62,30 @@ fn batch(req: &mut Request, engine: &Mutex<Exchange>) -> Reply {
if data.len() as u64 > MAX_BODY {
return Err((413, "Request body too large"));
}
let params = serde_json::from_slice(&data).map_err(|_| (400, "Invalid payload"))?;
query(engine, params, false)
serde_json::from_slice(&data).map_err(|_| (400, "Invalid payload"))
}
#[derive(Deserialize)]
struct TokenList {
token_ids: String,
}
fn last_prices(engine: &Mutex<Exchange>, tokens: Vec<String>, single: bool) -> Reply {
let mut rows = engine
.lock()
.map_err(|_| (500, "Internal server error"))?
.last_trade_prices(&tokens)
.map_err(|e| match e {
exchange::MarketDataError::Invalid(_) if single => (400, "Invalid token id"),
exchange::MarketDataError::Invalid(_) => (400, "Invalid payload"),
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
})?;
if single {
let row = rows.pop().ok_or((500, "Internal server error"))?;
Ok(json!({"price":row["price"],"side":row["side"]}))
} else {
Ok(Value::Array(rows))
}
}
fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
@@ -77,8 +99,31 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
(&Method::Get, "/book") => serde_urlencoded::from_str::<BookParam>(params)
.map_err(|_| (400, "Invalid token id"))
.and_then(|p| query(engine, vec![p], true)),
(&Method::Post, "/books") => batch(&mut req, engine),
(_, "/book" | "/v2/prices-history") => {
(&Method::Post, "/books") => batch_params(&mut req).and_then(|p| query(engine, p, false)),
(&Method::Get, "/last-trade-price") => serde_urlencoded::from_str::<BookParam>(params)
.map_err(|_| (400, "Invalid token id"))
.and_then(|p| last_prices(engine, vec![p.token_id], true)),
(&Method::Get, "/last-trades-prices") => serde_urlencoded::from_str::<TokenList>(params)
.map_err(|_| (400, "Invalid payload"))
.and_then(|p| {
last_prices(
engine,
p.token_ids.split(',').map(str::to_owned).collect(),
false,
)
}),
(&Method::Post, "/last-trades-prices") => batch_params(&mut req).and_then(|p| {
last_prices(
engine,
p.into_iter().map(|item| item.token_id).collect(),
false,
)
}),
(_, "/last-trades-prices") => {
allow = Some("GET, POST");
Err((405, "Method not allowed"))
}
(_, "/book" | "/last-trade-price" | "/v2/prices-history") => {
allow = Some("GET");
Err((405, "Method not allowed"))
}
@@ -172,7 +217,19 @@ mod tests {
let mixed = json!([
{"token_id":no}, {"token_id":"7"}, {"token_id":yes,"side":"BUY"}, {"token_id":no}
]);
let no_fills = json!({"price":"0.5","side":""});
let batch_no_fills = json!([{"token_id":yes,"price":"0.5","side":""},
{"token_id":no,"price":"0.5","side":""}]);
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 cases = [
("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)),
("GET","/last-trade-price?token_id=",String::new(),400,Some(json!({"error":"Invalid token id"}))),
("POST","/last-trades-prices",json!(too_many).to_string(),400,Some(json!({"error":"Invalid payload"}))),
("DELETE","/last-trades-prices",String::new(),405,None),
(
"GET",
encoded,
+21
View File
@@ -1005,3 +1005,24 @@ sequenceDiagram
R-->>W: 数据与内部继续位置
W-->>H: 公开点字段、偏移和 URL 安全的继续游标
```
### 最近成交价与方向
```mermaid
flowchart LR
H["cli/market_http.rs"] --> L["last_trades.rs"]
W["market_stream.rs"] -->|复用成交方向换算| L
L --> Q["last_trades.sql"]
```
```mermaid
sequenceDiagram
participant H as HTTP
participant L as last_trades
participant D as SQLite
H->>L: 请求资产列表
L->>D: 单条查询联结每个资产的最近成交、成交上下文和吃单委托
D-->>L: 成交价格及吃单方结果和方向
L->>L: 对互补结果反转方向;缺少吃单记录时方向留空
L-->>H: 按输入顺序返回,保留重复项
```
+45
View File
@@ -0,0 +1,45 @@
use crate::{assets, inventory, tick_size, Exchange, MarketDataError};
use serde_json::{json, Value};
/// For a paired fill, the other outcome sees the complementary side of the taker.
pub(crate) fn taker_side(
outcome: &str,
taker_outcome: Option<&str>,
side: Option<&str>,
) -> Option<&'static str> {
match (taker_outcome? == outcome, side?) {
(true, "buy") | (false, "sell") => Some("BUY"),
(true, "sell") | (false, "buy") => Some("SELL"),
_ => None,
}
}
impl Exchange {
/// Return one public last-trade row per requested asset from the same SQLite snapshot.
pub fn last_trade_prices(&self, tokens: &[String]) -> Result<Vec<Value>, MarketDataError> {
if !(1..=500).contains(&tokens.len()) {
return Err(MarketDataError::Invalid("expected 1 to 500 tokens".into()));
}
let assets = tokens
.iter()
.map(|token| assets::parse_id(token))
.collect::<anyhow::Result<Vec<_>>>()
.map_err(|_| MarketDataError::Invalid("Invalid token id".into()))?;
let input = serde_json::to_string(&assets).map_err(|_| MarketDataError::Unavailable)?;
let mut stmt = self.db.prepare_cached(include_str!("last_trades.sql"))?;
let mut rows = stmt.query([input])?;
let mut result = Vec::with_capacity(tokens.len());
for (token, (outcome, _)) in tokens.iter().zip(assets) {
let row = rows.next()?.ok_or(MarketDataError::Unavailable)?;
let p: Option<i64> = row.get(0)?;
let taker: Option<String> = row.get(1)?;
let side: Option<String> = row.get(2)?;
let price = p
.map(|p| inventory::decimal(p.into(), tick_size::PAR).to_string())
.unwrap_or_else(|| "0.5".into());
result.push(json!({"token_id":token, "price":price,
"side":taker_side(outcome,taker.as_deref(),side.as_deref()).unwrap_or("")}));
}
Ok(result)
}
}
+7
View File
@@ -0,0 +1,7 @@
SELECT l.price,t.outcome,t.side
FROM json_each(?1) AS asset
LEFT JOIN last_asset_trades l ON l.market=json_extract(asset.value,'$[1]')
AND l.outcome=json_extract(asset.value,'$[0]')
LEFT JOIN execution_context c ON c.execution=l.execution
LEFT JOIN orders t ON t.seq=c.taker_order
ORDER BY asset.key
+16 -1
View File
@@ -20,6 +20,7 @@ mod cancellation;
mod command;
mod inventory;
mod kickoff;
mod last_trades;
mod ledger;
mod lots;
mod market;
@@ -45,7 +46,21 @@ use std::{path::Path, time::Duration};
pub use assets::parse_id as parse_asset_id;
pub use depth_feed::MarketPage;
pub use prices_history::http::{HistoryError, HistoryQuery};
pub use prices_history::http::HistoryQuery;
#[derive(Debug)]
pub enum MarketDataError {
Invalid(String),
Unavailable,
}
impl From<rusqlite::Error> for MarketDataError {
fn from(_: rusqlite::Error) -> Self {
Self::Unavailable
}
}
pub type HistoryError = MarketDataError;
pub struct Exchange {
db: Connection,
+8 -3
View File
@@ -95,8 +95,7 @@ pub(crate) fn page(
fn trades(tx: &Transaction, market: &str, source: i64, fee_ppm: i64) -> Result<Vec<Value>> {
let mut stmt = tx.prepare_cached(
"SELECT p.outcome,p.at_ms,p.price_micros,p.quantity,
CASE WHEN t.outcome=p.outcome THEN upper(t.side)
WHEN t.side='buy' THEN 'SELL' WHEN t.side='sell' THEN 'BUY' END
t.outcome,t.side
FROM outcome_trade_prices p JOIN execution_context c ON c.execution=p.fill
LEFT JOIN orders t ON t.seq=c.taker_order WHERE p.fill=? ORDER BY p.outcome DESC",
)?;
@@ -107,7 +106,13 @@ fn trades(tx: &Transaction, market: &str, source: i64, fee_ppm: i64) -> Result<V
let stamp: i64 = r.get(1)?;
let price: i64 = r.get(2)?;
let quantity: i64 = r.get(3)?;
let side: Option<String> = r.get(4)?;
let taker_outcome: Option<String> = r.get(4)?;
let order_side: Option<String> = r.get(5)?;
let side = crate::last_trades::taker_side(
&outcome,
taker_outcome.as_deref(),
order_side.as_deref(),
);
frames.push(json!({"event_type":"last_trade_price","market":market,"asset_id":assets::id(market,&outcome),
"timestamp":stamp.to_string(),"price":decimal(price.into(),1_000_000).to_string(),
"size":decimal(quantity.into(),lots::PER_SHARE).to_string(),"side":side,
+1 -7
View File
@@ -1,5 +1,5 @@
use super::{Cursor, Request};
use crate::{assets, Exchange};
use crate::{assets, Exchange, HistoryError};
use anyhow::{ensure, Context, Result};
use data_encoding::BASE64URL_NOPAD;
use serde::{Deserialize, Serialize};
@@ -31,12 +31,6 @@ struct Continuation {
bucket_seconds: Option<i64>,
}
#[derive(Debug)]
pub enum HistoryError {
Invalid(String),
Unavailable,
}
impl Exchange {
pub fn public_price_history(&self, query: HistoryQuery) -> Result<Value, HistoryError> {
let tx = self
+24
View File
@@ -2910,13 +2910,37 @@ fn market_stream_preserves_trades_and_empty_book_tick_across_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("stream.db");
let mut writer = Exchange::open(&path).unwrap();
let yes = "eb:YES:demo".to_owned();
let no = "eb:NO:demo".to_owned();
let tokens = [no.clone(), yes.clone(), no.clone()];
for line in include_str!("../../../docs/examples/market-stream-trades.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
let result = writer.execute(cmd.clone()).unwrap();
if cmd["id"] == "maker-ask" {
let prices = writer.last_trade_prices(&tokens).unwrap();
assert_eq!(prices[1], json!({"token_id":yes,"price":"0.5","side":""}));
} else if cmd["id"] == "buy" || cmd["id"] == "no" {
let prices = writer.last_trade_prices(&tokens).unwrap();
assert_eq!(
prices[1],
json!({"token_id":yes,"price":"0.4","side":"BUY"})
);
assert_eq!(prices[0], json!({"token_id":no,"price":"0.5","side":""}));
}
assert_eq!(writer.execute(cmd).unwrap(), result);
}
drop(writer);
let mut reader = Exchange::open(&path).unwrap();
let prices = reader.last_trade_prices(&tokens).unwrap();
assert_eq!(
prices[0],
json!({"token_id":no,"price":"0.65","side":"SELL"})
);
assert_eq!(
prices[1],
json!({"token_id":yes,"price":"0.35","side":"BUY"})
);
assert_eq!(prices[0], prices[2]);
let page = reader.market_stream_page("demo", Some(0)).unwrap();
let kinds: Vec<_> = page
.frames