Expose paginated account orders and terminal order lookup
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
use crate::validation::identifier;
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Filter {
|
||||
account: String,
|
||||
market: Option<String>,
|
||||
outcome: Option<String>,
|
||||
order: Option<i64>,
|
||||
#[serde(default)]
|
||||
after: i64,
|
||||
limit: Option<u32>,
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
pub(crate) fn read(self, db: &Connection) -> Result<Value> {
|
||||
identifier(&self.account)?;
|
||||
if let Some(market) = &self.market {
|
||||
identifier(market)?;
|
||||
}
|
||||
if let Some(outcome) = &self.outcome {
|
||||
ensure!(self.market.is_some(), "outcome requires market");
|
||||
ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome");
|
||||
}
|
||||
if let Some(order) = self.order {
|
||||
ensure!(order > 0, "invalid order");
|
||||
}
|
||||
let limit = self.limit.unwrap_or(100);
|
||||
ensure!(
|
||||
self.after >= 0 && (1..=1000).contains(&limit),
|
||||
"invalid pagination"
|
||||
);
|
||||
|
||||
// Use the live-account index for pages and the primary key for an exact lookup.
|
||||
let scope = if self.order.is_some() {
|
||||
"seq=?6"
|
||||
} else {
|
||||
"status='live' AND ?6 IS NULL"
|
||||
};
|
||||
let sql = format!(
|
||||
"SELECT seq,market,outcome,side,price,quantity,remaining,status FROM orders
|
||||
WHERE account=?1 AND (?2 IS NULL OR market=?2) AND (?3 IS NULL OR outcome=?3)
|
||||
AND seq>?4 AND {scope} ORDER BY seq LIMIT ?5"
|
||||
);
|
||||
let mut stmt = db.prepare(&sql)?;
|
||||
let mut rows = stmt.query(params![
|
||||
self.account,
|
||||
self.market,
|
||||
self.outcome,
|
||||
self.after,
|
||||
limit + 1,
|
||||
self.order
|
||||
])?;
|
||||
let mut orders = Vec::new();
|
||||
let mut last_id = None;
|
||||
let mut next_after = None;
|
||||
while let Some(row) = rows.next()? {
|
||||
if orders.len() == limit as usize {
|
||||
next_after = last_id;
|
||||
break;
|
||||
}
|
||||
let id: i64 = row.get(0)?;
|
||||
let quantity: i64 = row.get(5)?;
|
||||
let remaining: i64 = row.get(6)?;
|
||||
let status: String = row.get(7)?;
|
||||
orders.push(json!({"order":id,"market":row.get::<_,String>(1)?,
|
||||
"outcome":row.get::<_,String>(2)?,"side":row.get::<_,String>(3)?,
|
||||
"price_micros":row.get::<_,i64>(4)?*10000,"original_size":quantity,
|
||||
"size_matched":quantity-remaining,"open_size":if status=="live"{remaining}else{0},
|
||||
"status":status}));
|
||||
last_id = Some(id);
|
||||
}
|
||||
Ok(json!({"orders":orders,"next_after":next_after}))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user