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