Reconcile precise collateral funding, fee debits and available cash
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Transaction};
|
||||
use rusqlite::{params, Connection, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn cash(tx: &Transaction, account: &str, delta: i64) -> Result<()> {
|
||||
ensure!(
|
||||
@@ -12,6 +13,41 @@ pub(crate) fn cash(tx: &Transaction, account: &str, delta: i64) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Keep the legacy whole-cent column and the sub-cent remainder canonical.
|
||||
pub(crate) fn cash_micros(tx: &Transaction, account: &str, delta: i64) -> Result<()> {
|
||||
if delta % 10000 == 0 {
|
||||
return cash(tx, account, delta / 10000);
|
||||
}
|
||||
let old: i64 = tx.query_row(
|
||||
"SELECT COALESCE((SELECT micros FROM cash_remainders WHERE account=?),0)",
|
||||
[account],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let remainder = old + delta.rem_euclid(10000);
|
||||
cash(tx, account, delta.div_euclid(10000) + remainder / 10000)?;
|
||||
tx.execute("INSERT INTO cash_remainders(account,micros) VALUES(?,?) ON CONFLICT(account) DO UPDATE SET micros=excluded.micros",
|
||||
params![account, remainder % 10000])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn balance(db: &Connection, account: &str) -> Result<Value> {
|
||||
crate::validation::identifier(account)?;
|
||||
let (cash, remainder, reserved): (i64, i64, i64) = db.query_row(
|
||||
"SELECT a.cash,COALESCE(r.micros,0),
|
||||
(SELECT COALESCE(SUM(price*remaining),0) FROM orders
|
||||
WHERE account=a.id AND side='buy' AND status='live')
|
||||
FROM accounts a LEFT JOIN cash_remainders r ON r.account=a.id WHERE a.id=?",
|
||||
[account],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
let available = i128::from(cash) * 10000 + i128::from(remainder);
|
||||
let reserved = i128::from(reserved) * 10000;
|
||||
Ok(
|
||||
json!({"account":account, "available_micros":available, "reserved_micros":reserved,
|
||||
"total_cash_micros":available+reserved}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn position(
|
||||
tx: &Transaction,
|
||||
account: &str,
|
||||
|
||||
Reference in New Issue
Block a user