市场成交与持仓数据及含吃单手续费的本地交割 #7
@@ -209,3 +209,16 @@ sequenceDiagram
|
||||
```
|
||||
|
||||
[可重放请求](../../docs/examples/clob-http.http)同时展示相同盘口下的买价、卖价与中点。
|
||||
|
||||
### CLOB 客户端历史曲线
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as CLOB 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as prices_history/legacy.rs
|
||||
C->>H: GET /prices-history,market 与 interval 或 startTs、endTs
|
||||
H->>E: clob_price_history,fidelity 以分钟计
|
||||
E-->>H: 按观测时刻排序的价格点
|
||||
H-->>C: history 数组,每点包含 t 和 p
|
||||
```
|
||||
|
||||
@@ -284,6 +284,23 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
allow = Some("GET");
|
||||
Err((405, "Method not allowed"))
|
||||
}
|
||||
(&Method::Get, "/prices-history") => {
|
||||
let result = serde_urlencoded::from_str::<exchange::ClobHistoryQuery>(params)
|
||||
.map_err(|_| HistoryError::Invalid("invalid query parameters".into()))
|
||||
.and_then(|query| {
|
||||
engine
|
||||
.lock()
|
||||
.map_err(|_| HistoryError::Unavailable)?
|
||||
.clob_price_history(query)
|
||||
});
|
||||
match result {
|
||||
Ok(history) => Ok(history),
|
||||
Err(HistoryError::Invalid(message)) => {
|
||||
return send(req, 400, json!({"error":message}), None)
|
||||
}
|
||||
Err(HistoryError::Unavailable) => Err((500, "Internal server error")),
|
||||
}
|
||||
}
|
||||
(&Method::Get, "/price") => serde_urlencoded::from_str::<WirePrice>(params)
|
||||
.map_err(|_| (400, "Invalid token id"))
|
||||
.and_then(|p| execution_prices(engine, vec![p], true)),
|
||||
@@ -361,7 +378,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
}
|
||||
(
|
||||
_,
|
||||
"/price" | "/midpoint" | "/spread" | "/book" | "/last-trade-price"
|
||||
"/price" | "/midpoint" | "/spread" | "/book" | "/last-trade-price" | "/prices-history"
|
||||
| "/v2/prices-history",
|
||||
) => {
|
||||
allow = Some("GET");
|
||||
@@ -488,6 +505,12 @@ mod tests {
|
||||
let price_batch =
|
||||
json!({"eb:YES:mid-example":{"BUY":0.09,"SELL":0.08},"eb:NO:mid-example":{"BUY":0.92}});
|
||||
let cases = [
|
||||
("GET","/prices-history?market=eb:YES:s&interval=1h&fidelity=10",String::new(),200,Some(json!({"history":[]}))),
|
||||
("GET","/prices-history?market=eb:NO:s&startTs=1000&endTs=2000",String::new(),200,Some(json!({"history":[]}))),
|
||||
("GET","/prices-history?market=eb:YES:s&startTs=1000",String::new(),400,None),
|
||||
("GET","/prices-history?market=eb:YES:s&interval=1d&fidelity=0",String::new(),400,None),
|
||||
("GET","/prices-history?market=eb:YES:s&startTs=1&endTs=2&interval=max",String::new(),400,None),
|
||||
("POST","/prices-history","{}".into(),405,None),
|
||||
("GET","/price?token_id=eb:YES:mid-example&side=BUY",String::new(),200,Some(json!({"price":"0.09"}))),
|
||||
("GET","/price?token_id=eb:YES:mid-example&side=SELL",String::new(),200,Some(json!({"price":"0.08"}))),
|
||||
("GET","/price?token_id=eb:YES:one&side=SELL",String::new(),200,Some(json!({"price":"0.20"}))),
|
||||
|
||||
@@ -1111,3 +1111,26 @@ sequenceDiagram
|
||||
D-->>Q: 返回买一与卖一
|
||||
Q-->>H: 按资产和方向分组的可用价格
|
||||
```
|
||||
|
||||
### CLOB 历史交易价格
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["cli/market_http.rs"] --> L["prices_history/legacy.rs"]
|
||||
L --> A["assets.rs"]
|
||||
L --> Q["prices_history/legacy.sql"]
|
||||
Q --> T["price_migration.sql 中的 outcome_trade_prices"]
|
||||
Q --> S["schema.sql 中的 price_settlements"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as HTTP
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
C->>E: clob_price_history
|
||||
E->>D: 读事务中确认资产并取得当前时钟
|
||||
E->>D: 按查询窗口和分钟粒度选每个桶内最后一个成交或兑付
|
||||
D-->>E: 观测时间和定点价格
|
||||
E-->>C: t 为 Unix 秒,p 为十进制数
|
||||
```
|
||||
|
||||
@@ -48,6 +48,7 @@ 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::HistoryQuery;
|
||||
pub use prices_history::legacy::ClobHistoryQuery;
|
||||
pub use quotes::{PriceQueryError, PriceRequest, PriceSide};
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub(crate) mod http;
|
||||
pub(crate) mod legacy;
|
||||
use anyhow::{bail, ensure, Result};
|
||||
use rusqlite::{params, Connection, Row};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
use crate::{assets, inventory, Exchange, HistoryError};
|
||||
use rusqlite::params;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ClobHistoryQuery {
|
||||
market: String,
|
||||
#[serde(rename = "startTs")]
|
||||
start: Option<f64>,
|
||||
#[serde(rename = "endTs")]
|
||||
end: Option<f64>,
|
||||
interval: Option<String>,
|
||||
fidelity: Option<i64>,
|
||||
}
|
||||
|
||||
impl ClobHistoryQuery {
|
||||
fn bounds(&self, now: i64) -> Result<(i64, i64), HistoryError> {
|
||||
let invalid = || HistoryError::Invalid("invalid price history window".into());
|
||||
match (self.interval.as_deref(), self.start, self.end) {
|
||||
(Some(interval), None, None) => {
|
||||
let span = match interval {
|
||||
"1h" => 3600,
|
||||
"6h" => 6 * 3600,
|
||||
"1d" => super::DAY,
|
||||
"1w" => 7 * super::DAY,
|
||||
"1m" => 30 * super::DAY,
|
||||
"max" | "all" => return Ok((0, now)),
|
||||
_ => return Err(invalid()),
|
||||
};
|
||||
Ok(((now - span * 1000).max(0), now))
|
||||
}
|
||||
(None, Some(start), Some(end))
|
||||
if start.is_finite()
|
||||
&& start >= 0.0
|
||||
&& start < end
|
||||
&& end <= f64::from(u32::MAX) =>
|
||||
{
|
||||
Ok((boundary_ms(start, f64::ceil), boundary_ms(end, f64::floor)))
|
||||
}
|
||||
_ => Err(invalid()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Multiplying a decimal timestamp such as 1.001 by 1000 can land below its
|
||||
// exact millisecond. Preserve that point before rounding sub-ms boundaries.
|
||||
fn boundary_ms(seconds: f64, round: fn(f64) -> f64) -> i64 {
|
||||
let ms = seconds * 1000.0;
|
||||
let nearest = ms.round() as i64;
|
||||
if nearest as f64 / 1000.0 == seconds {
|
||||
nearest
|
||||
} else {
|
||||
round(ms) as i64
|
||||
}
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn clob_price_history(&self, query: ClobHistoryQuery) -> Result<Value, HistoryError> {
|
||||
let (outcome, market) = assets::parse_id(&query.market)
|
||||
.map_err(|_| HistoryError::Invalid("invalid market asset id".into()))?;
|
||||
let width = query
|
||||
.fidelity
|
||||
.unwrap_or(1)
|
||||
.checked_mul(60)
|
||||
.filter(|n| *n > 0)
|
||||
.ok_or_else(|| HistoryError::Invalid("invalid fidelity".into()))?;
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let (listed, now): (bool, i64) = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1), CAST(unixepoch('subsec') * 1000 AS INTEGER)",
|
||||
[market], |r| Ok((r.get(0)?, r.get(1)?))
|
||||
)?;
|
||||
if !listed {
|
||||
return Err(HistoryError::Invalid("unknown market asset id".into()));
|
||||
}
|
||||
let (start, end) = query.bounds(now)?;
|
||||
let points = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("legacy.sql"))?;
|
||||
let rows = stmt.query_map(params![market, outcome, start, end, width], |r| {
|
||||
let timestamp: i64 = r.get(0)?;
|
||||
let micros: i64 = r.get(1)?;
|
||||
Ok(json!({"t":timestamp,"p":inventory::decimal(micros.into(), inventory::UNIT)}))
|
||||
})?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
tx.commit()?;
|
||||
Ok(json!({"history":points}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Return the last observed price in each UTC fidelity window at its actual time.
|
||||
WITH observations(ms, micros, sequence, payout) AS (
|
||||
SELECT at_ms, price_micros, fill, 0 FROM outcome_trade_prices
|
||||
WHERE market=?1 AND outcome=?2 AND at_ms BETWEEN ?3 AND ?4
|
||||
UNION ALL
|
||||
SELECT at_ms, CASE WHEN winner='VOID' THEN 500000 WHEN winner=?2 THEN 1000000 ELSE 0 END, id, 1
|
||||
FROM price_settlements WHERE market=?1 AND at_ms BETWEEN ?3 AND ?4
|
||||
), ranked AS (
|
||||
SELECT ms, micros, ROW_NUMBER() OVER (
|
||||
PARTITION BY ms/1000/?5 ORDER BY ms DESC, payout DESC, sequence DESC
|
||||
) AS position FROM observations
|
||||
)
|
||||
SELECT ms/1000, micros FROM ranked WHERE position=1 ORDER BY ms
|
||||
@@ -1532,6 +1532,25 @@ fn prices_history_keeps_the_terminal_tick_and_pins_pages_before_settlement() {
|
||||
let wire = |engine: &Exchange, params: Value| {
|
||||
engine.public_price_history(serde_json::from_value(params).unwrap())
|
||||
};
|
||||
let clob = |engine: &Exchange, start: f64, end: f64, minutes: i64| {
|
||||
engine
|
||||
.clob_price_history(
|
||||
serde_json::from_value(json!({
|
||||
"market":"eb:YES:e","startTs":start,"endTs":end,"fidelity":minutes
|
||||
}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
clob(&e, 120.0, 245.0, 1),
|
||||
json!({"history":[{"t":149,"p":0.47},{"t":245,"p":0.55}]})
|
||||
);
|
||||
assert_eq!(clob(&e, 149.001, 244.999, 1), json!({"history":[]}));
|
||||
assert_eq!(
|
||||
clob(&e, 120.0, 245.0, 10),
|
||||
json!({"history":[{"t":245,"p":0.55}]})
|
||||
);
|
||||
let first_wire = wire(
|
||||
&e,
|
||||
json!({"tokenId":"eb:YES:e","start":120,"end":290,"bucketSeconds":60,"limit":1}),
|
||||
@@ -1563,6 +1582,10 @@ fn prices_history_keeps_the_terminal_tick_and_pins_pages_before_settlement() {
|
||||
.unwrap();
|
||||
drop(e);
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
assert_eq!(
|
||||
clob(&e, 120.0, 290.0, 1),
|
||||
json!({"history":[{"t":149,"p":0.47},{"t":273,"p":0.5}]})
|
||||
);
|
||||
let second_wire = wire(
|
||||
&e,
|
||||
json!({"token_id":"eb:YES:e","start":120,"end":290,"cursor":saved,"limit":99}),
|
||||
|
||||
@@ -72,3 +72,9 @@ POST http://127.0.0.1:9002/prices
|
||||
Content-Type: application/json
|
||||
|
||||
[{"token_id":"eb:YES:mid-example","side":"BUY"},{"token_id":"eb:NO:mid-example","side":"BUY"}]
|
||||
|
||||
### CLOB SDK time series: asset ID, trailing hour, ten-minute fidelity
|
||||
GET http://127.0.0.1:9002/prices-history?market=eb%3AYES%3Ademo&interval=1h&fidelity=10
|
||||
|
||||
### Explicit Unix-second window (the seeded exchange regression has fills at 121, 149 and 245)
|
||||
GET http://127.0.0.1:9002/prices-history?market=eb%3AYES%3Ae&startTs=120&endTs=245&fidelity=1
|
||||
|
||||
@@ -369,3 +369,11 @@ Polymarket 的单资产最近成交接口规定,无成交时返回价格字符
|
||||
用[同一份本地盘口](examples/midpoint.jsonl)重放:YES 买一 0.08、卖一 0.09。单查 BUY 返回 {"price":"0.09"},单查 SELL 返回 {"price":"0.08"}。批量查询同一结果的两个方向会保留两个键,价格为 JSON 数字。GET 的 token_ids、sides 两列按位置配对,POST 接收含 token_id 和 side 的对象数组。[HTTP 请求](examples/clob-http.http) · [批量 GET 规范](https://docs.polymarket.com/api-reference/market-data/get-market-prices-query-parameters) · [批量 POST 规范](https://docs.polymarket.com/api-reference/market-data/get-market-prices-request-body)
|
||||
|
||||
官方行情指南从交易者角度描述 BUY 取卖一,OpenAPI 的单查文字则把 BUY 对应到买一。本地沿用行情指南与既有交易命令的口径。官方 Rust SDK 的模拟回执可以确认单查字符串、批查数字,无法据此判定生产方向。已上市资产缺少所需一侧时,本地 HTTP 单查返回 422,批查省略该方向。请求中出现未上市资产时整批返回 404。上述边界和交易方向仍待稳定盘口实测。[行情指南](https://docs.polymarket.com/market-data/prices-order-books#best-market-price) · [单查规范](https://docs.polymarket.com/api-reference/market-data/get-market-price) · [官方 SDK 用例](https://github.com/Polymarket/rs-clob-client-v2/blob/main/tests/clob.rs#L139-L216)
|
||||
|
||||
### CLOB 历史价格曲线
|
||||
|
||||
旧版 CLOB 客户端通过 `GET /prices-history` 发送结果资产 ID(参数名 market)。它可以传 interval,或传 startTs 和 endTs。时间戳以 Unix 秒计,fidelity 以分钟计,省略时本地采用 1 分钟。返回对象的 history 数组按时间升序排列,t 为秒,p 为 JSON 数字。[CLOB OpenAPI](https://docs.polymarket.com/api-reference/markets/get-prices-history) · [SDK 请求和响应测试](https://github.com/Polymarket/rs-clob-client-v2/blob/main/tests/clob.rs#L219-L294) · [HTTP 样例](examples/clob-http.http)
|
||||
|
||||
本地以每个 UTC 采样窗口内最后一笔真实成交或模拟兑付为观测,保留其发生时刻。区间包含两端,只挂单的市场返回空数组。以第 121、149、245 秒的三个成交为例,1 分钟粒度返回第 149、245 秒两点,10 分钟粒度仅返回第 245 秒。市场作废时以实际裁决时刻记录 0.5。同毫秒的成交按执行序号排序,兑付优先。这个数据源、采样时刻和端点包含规则尚待生产逐点核对。
|
||||
|
||||
官方 SDK 仓库有用户在同一已裁决资产上记录了两种结果:max 窗口按 60 分钟查询返回空,按 720 分钟查询有历史;后来该用户用显式起止时间取得更细数据。本地可返回已保存的全部历史。这项生产覆盖差异仍然存在。[原报告及后续复查](https://github.com/Polymarket/py-clob-client/issues/216)
|
||||
|
||||
Reference in New Issue
Block a user