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,
|
||||
|
||||
@@ -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: 按输入顺序返回,保留重复项
|
||||
```
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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,
|
||||
|
||||
@@ -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,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -15,3 +15,15 @@ GET http://127.0.0.1:9002/v2/prices-history?token_id=eb%3AYES%3Ademo&interval=1h
|
||||
|
||||
### Replace the cursor placeholder with pagination.next_cursor from the previous response
|
||||
GET http://127.0.0.1:9002/v2/prices-history?token_id=eb%3AYES%3Ademo&cursor={{next_cursor}}
|
||||
|
||||
### Last execution for one outcome
|
||||
GET http://127.0.0.1:9002/last-trade-price?token_id=eb%3AYES%3Ademo
|
||||
|
||||
### Last executions for both outcomes from one SQLite snapshot
|
||||
GET http://127.0.0.1:9002/last-trades-prices?token_ids=eb%3AYES%3Ademo%2Ceb%3ANO%3Ademo
|
||||
|
||||
### Batch last executions in JSON
|
||||
POST http://127.0.0.1:9002/last-trades-prices
|
||||
Content-Type: application/json
|
||||
|
||||
[{"token_id":"eb:YES:demo"},{"token_id":"eb:NO:demo"}]
|
||||
|
||||
@@ -333,3 +333,9 @@ order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可
|
||||
`GET /v2/prices-history` 接受 token_id 或 tokenId,支持绝对窗口、相对 interval 及 as_of / asOf。桶宽使用 bucket_seconds 或 bucketSeconds。响应公开 timestamp、price、resolution_seconds 以及 pagination。客户端可在重启后用同一资产继续翻页;即使新成交或裁决已经写入,后续页仍使用首页的序号上限。续页可重发相同窗口,页大小沿用首页。本地 limit=0 返回空页;这一边界仍待现场比对。
|
||||
|
||||
目前点来自 Eventbook 成交与模拟兑付。数据库保存本地历史,尚未复现生产分层行情的实际覆盖范围、过期细粒度查询或链上兑付确认时点。官方文档把可用粒度与具体时间窗绑定,单凭响应形状无法验证价格曲线一致。[V2 价格历史](https://docs.polymarket.com/api-reference/markets/get-a-tokens-price-history) · [请求样例](examples/clob-http.http)
|
||||
|
||||
## 挂单、展示价和最近成交
|
||||
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user