Serve last execution prices and directions for individual and batch token queries
This commit is contained in:
@@ -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 的数组
|
||||
```
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user