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