Files
eventbook-exchange/crates/exchange/src/portfolio.rs
T

166 lines
5.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
pub(crate) mod http;
mod protocol;
use crate::{
inventory::{decimal, UNIT},
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>,
status: Option<String>,
after: Option<(SortKey, String, String)>,
limit: Option<u32>,
}
#[derive(serde::Serialize, Deserialize)]
#[serde(untagged)]
enum SortKey {
Legacy(i64),
Fraction { micros: i64 },
}
impl SortKey {
fn units(&self, status: &str) -> Result<i64> {
match self {
Self::Legacy(key) if status == "MERGEABLE" => key
.checked_mul(UNIT)
.ok_or_else(|| anyhow::anyhow!("position cursor overflow")),
Self::Legacy(key) => Ok(*key),
Self::Fraction { micros } if status == "MERGEABLE" => Ok(*micros),
_ => anyhow::bail!("invalid position cursor"),
}
}
}
impl Filter {
pub(crate) fn read(self, db: &Connection) -> Result<Value> {
identifier(&self.account)?;
if let Some(market) = &self.market {
identifier(market)?;
}
let status = self.status.as_deref().unwrap_or("OPEN");
ensure!(
matches!(
status,
"OPEN" | "CLOSED" | "REDEEMABLE" | "REDEEMABLE_LOST" | "MERGEABLE"
),
"invalid position status"
);
let limit = self.limit.unwrap_or(100);
ensure!((1..=1000).contains(&limit), "invalid page size");
let cursor = self.after.as_ref();
let mut stmt = db.prepare(include_str!("portfolio.sql"))?;
let mut rows = stmt.query(params![
self.account,
self.market,
status,
cursor.map(|c| c.0.units(status)).transpose()?,
cursor.map(|c| c.1.as_str()),
cursor.map(|c| c.2.as_str()),
limit + 1
])?;
let mut positions = Vec::new();
let mut last = None;
let mut next_after = None;
while let Some(row) = rows.next()? {
if positions.len() == limit as usize {
next_after = last;
break;
}
let market: String = row.get(0)?;
let outcome: String = row.get(1)?;
let size: i64 = row.get(2)?;
let row_status: String = row.get(5)?;
let payout: Option<i64> = row.get(6)?;
let pairs: i64 = row.get(7)?;
let phase: String = row.get(13)?;
let (mark, source) = price(db, &market, &outcome, &phase, payout)?.unzip();
positions.push(json!({
"current_price_micros":mark,"price_source":source,"current_value_micros":holding_value(size,mark),
"asset_id":crate::assets::id(&market,&outcome),"market":market, "outcome":outcome, "status":row_status, "size":decimal(size.into(),UNIT),
"neg_risk_group":row.get::<_,Option<String>>(10)?,
"augmented_role":row.get::<_,Option<String>>(11)?,"outcome_name":row.get::<_,Option<String>>(12)?,
"available_size":decimal(row.get::<_,i64>(3)?.into(),UNIT), "reserved_size":decimal(row.get::<_,i64>(4)?.into(),UNIT),
"redeemable":row_status=="REDEEMABLE", "payout_cents":payout.map(|p|decimal(i128::from(p)*i128::from(size)/100,10000)),
"mergeable":pairs>0, "available_pairs":decimal(row.get::<_,i64>(8)?.into(),UNIT)
}));
let key: i64 = row.get(9)?;
let sort = if status != "MERGEABLE" {
SortKey::Legacy(key)
} else if key % UNIT == 0 {
SortKey::Legacy(key / UNIT)
} else {
SortKey::Fraction { micros: key }
};
last = Some((sort, market, outcome));
}
Ok(json!({"positions":positions,"next_after":next_after}))
}
}
pub(crate) fn price(
db: &Connection,
market: &str,
outcome: &str,
phase: &str,
payout: Option<i64>,
) -> Result<Option<(i64, &'static str)>> {
if let Some(p) = payout {
return Ok(Some((p * 10000, "settlement")));
}
Ok(crate::quotes::Quote::current(db, market, outcome)?.mark(phase))
}
pub(crate) fn holding_value(size: i64, mark: Option<i64>) -> Option<i128> {
if size == 0 {
return Some(0);
}
mark.map(|p| i128::from(p) * i128::from(size) / i128::from(UNIT))
}
/// Total in units of (micro-share × micro-dollar per share), before final rounding.
fn marked_holdings(
db: &Connection,
account: &str,
conditions: Option<&str>,
wallet_address: bool,
) -> Result<(i128, u64)> {
let mut stmt = db.prepare_cached(include_str!("portfolio/value.sql"))?;
let mut rows = stmt.query(params![account, conditions, wallet_address])?;
let mut priced = 0i128;
let mut missing = 0u64;
while let Some(row) = rows.next()? {
let market: String = row.get(0)?;
let outcome: String = row.get(1)?;
let phase: String = row.get(3)?;
let mark = price(db, &market, &outcome, &phase, row.get(4)?)?.map(|(p, _)| p);
let size: i64 = row.get(2)?;
match mark.map(|price| i128::from(price) * i128::from(size)) {
Some(amount) => {
priced = priced
.checked_add(amount)
.ok_or_else(|| anyhow::anyhow!("portfolio value overflow"))?
}
None => missing += 1,
}
}
Ok((priced, missing))
}
pub(crate) fn value(db: &Connection, account: &str) -> Result<Value> {
identifier(account)?;
let (priced, missing) = marked_holdings(db, account, None, false)?;
let priced = priced / i128::from(UNIT);
Ok(
json!({"account":account,"value_micros":(missing==0).then_some(priced),
"priced_value_micros":priced,"unpriced_positions":missing}),
)
}