Reconcile precise collateral funding, fee debits and available cash

This commit is contained in:
2026-12-03 06:30:11 +08:00
parent 2fcdac61d5
commit 14ccc97e09
14 changed files with 207 additions and 41 deletions
+3 -1
View File
@@ -106,9 +106,11 @@ impl Filter {
.map(|(m, o)| assets::id(m, o));
let fee: i64 = r.get(14)?;
let cash: i64 = r.get(9)?;
let precise_deposit: Option<i64> = r.get(15)?;
let gross = precise_deposit.map_or(i128::from(cash) * 10000, i128::from);
items.push(json!({"type":r.get::<_,String>(5)?,"account":self.account,"at_ms":r.get::<_,Option<i64>>(4)?,
"market":market,"group":r.get::<_,Option<String>>(7)?,"asset_id":asset,"outcome":outcome,
"shares":r.get::<_,Option<i64>>(8)?,"cash_delta_cents":cash,"fee_micros":fee,"net_cash_delta_micros":i128::from(cash)*10000-i128::from(fee),
"shares":r.get::<_,Option<i64>>(8)?,"cash_delta_cents":cash,"fee_micros":fee,"net_cash_delta_micros":gross-i128::from(fee),
"side":r.get::<_,Option<String>>(12)?,"price_micros":r.get::<_,Option<i64>>(13)?.map(|p|p*10000),
"request_id":r.get::<_,Option<String>>(10)?,"execution":(source==1).then_some(seq),"order":(source==1).then_some(leg)}));
last = Some(Cursor {
+3 -1
View File
@@ -7,7 +7,9 @@ WITH activity(source,seq,leg,at_ms,kind,market,group_id,shares,cash_delta,reques
FROM wallet_trade_legs WHERE account=?1
)
SELECT COALESCE(at_ms,-1) AS ts,source,seq,leg,at_ms,kind,market,group_id,shares,cash_delta,request_id,outcome,side,price,
COALESCE((SELECT fee_micros FROM execution_fees WHERE source=1 AND execution=seq AND taker_order=leg),0)
COALESCE((SELECT fee_micros FROM execution_fees WHERE source=1 AND execution=seq AND taker_order=leg),0),
CASE WHEN kind='DEPOSIT' THEN (SELECT json_extract(response,'$.funded_micros')
FROM requests WHERE id=activity.request_id) END
FROM activity
WHERE (?2 IS NULL OR market=?2)
AND (?3 IS NULL OR kind IN (SELECT value FROM json_each(?3)))
+5 -4
View File
@@ -143,7 +143,9 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
release(tx, seq, &account, CancelReason::Cancelled)?;
status = "cancelled".into();
}
crate::fees::debit(tx, &account, fee_micros)?;
if fee_micros > 0 {
ledger::cash_micros(tx, &account, -fee_micros)?;
}
Ok(ShareExecution {
fee_micros,
seq,
@@ -219,8 +221,7 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
params![seq, amount_cents, spent],
)?;
let fee = settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?;
ledger::cash(tx, &account, gross_remainder)?;
crate::fees::debit(tx, &account, fee)?;
ledger::cash_micros(tx, &account, gross_remainder * 10000 - fee)?;
let status = if unspent_micros == 0 {
"filled"
} else {
@@ -357,7 +358,7 @@ pub(crate) fn settle(
params![execution, taker.map(Taker::seq)],
)?;
if let Some(taker) = taker {
let fee = crate::fees::micros(rate, f.price, f.quantity);
let fee = crate::fees::micros(rate, f.price * 10000, f.quantity);
if fee > 0 {
tx.execute(
"INSERT INTO execution_fees VALUES(?,?,?)",
+4
View File
@@ -254,6 +254,9 @@ pub(crate) enum Query {
Positions(crate::portfolio::Filter),
OpenInterest(crate::open_interest::Request),
Holders(crate::holders::Request),
Balance {
account: String,
},
PortfolioValue {
account: String,
},
@@ -305,6 +308,7 @@ impl Query {
Self::Resolution { market } => crate::resolution::read(db, &market),
Self::Assets { market } => assets::market_assets(db, &market),
Self::Activity(filter) => filter.read(db),
Self::Balance { account } => crate::ledger::balance(db, &account),
Self::PortfolioValue { account } => crate::portfolio::value(db, &account),
Self::Holders(request) => request.read(db),
Self::OpenInterest(request) => request.read(db),
+2 -1
View File
@@ -5,7 +5,8 @@ use serde::Deserialize;
pub(crate) enum Command {
Fund {
account: String,
cents: i64,
cents: Option<i64>,
micros: Option<i64>,
},
Event(crate::catalog::Event),
List {
+17 -27
View File
@@ -1,4 +1,3 @@
use crate::ledger;
use anyhow::{ensure, Result};
use matching::Fill;
use rusqlite::{params, Connection, Transaction};
@@ -7,21 +6,24 @@ pub(crate) fn rate(db: &Connection, market: &str) -> Result<i64> {
Ok(db.query_row("SELECT COALESCE(f.rate_ppm,0) FROM markets m LEFT JOIN market_fee_rates f ON f.market=m.id WHERE m.id=?", [market], |r|r.get(0))?)
}
// rate is parts per million; prices are cents. Round each fill to units of
// ten micros, suppressing amounts below the published minimum.
pub(crate) fn micros(rate: i64, price: i64, shares: i64) -> i64 {
let numerator =
i128::from(shares) * i128::from(rate) * i128::from(price) * i128::from(100 - price);
if numerator < 100_000 {
// Price and rate both have six decimals. Round the fee only after the
// complete fill, to the nearest ten micros, with the published minimum.
pub(crate) fn micros(rate: i64, price_micros: i64, shares: i64) -> i64 {
let numerator = i128::from(shares)
* i128::from(rate)
* i128::from(price_micros)
* i128::from(1_000_000 - price_micros);
let denominator = 10_000_000_000_000;
if numerator < denominator {
return 0;
}
(((numerator + 50_000) / 100_000) * 10) as i64
(((numerator + denominator / 2) / denominator) * 10) as i64
}
pub(crate) fn total(rate: i64, fills: &[Fill]) -> i64 {
fills
.iter()
.map(|f| micros(rate, f.price, f.quantity))
.map(|f| micros(rate, f.price * 10000, f.quantity))
.sum()
}
@@ -35,7 +37,8 @@ pub(crate) fn fit_budget(rate: i64, fills: &mut Vec<Fill>, budget: i64) {
let mut count = 0;
for f in fills.iter_mut() {
let cost = |qty: i64| {
i128::from(qty) * i128::from(f.price) * 10000 + i128::from(micros(rate, f.price, qty))
i128::from(qty) * i128::from(f.price) * 10000
+ i128::from(micros(rate, f.price * 10000, qty))
};
if cost(f.quantity) <= i128::from(remaining) {
remaining -= cost(f.quantity) as i64;
@@ -60,21 +63,6 @@ pub(crate) fn fit_budget(rate: i64, fills: &mut Vec<Fill>, budget: i64) {
fills.truncate(count);
}
pub(crate) fn debit(tx: &Transaction, account: &str, fee: i64) -> Result<()> {
if fee == 0 {
return Ok(());
}
let old: i64 = tx.query_row(
"SELECT COALESCE((SELECT micros FROM cash_remainders WHERE account=?),0)",
[account],
|r| r.get(0),
)?;
let delta = old - fee;
ledger::cash(tx, account, delta.div_euclid(10000))?;
tx.execute("INSERT INTO cash_remainders(account,micros) VALUES(?,?) ON CONFLICT(account) DO UPDATE SET micros=excluded.micros",params![account,delta.rem_euclid(10000)])?;
Ok(())
}
pub(crate) fn configure(tx: &Transaction, market: &str, rate: i64) -> Result<()> {
ensure!((0..=1_000_000).contains(&rate), "invalid taker fee rate");
tx.execute(
@@ -90,6 +78,8 @@ mod tests {
#[test]
fn symmetric_taker_curve_matches_published_examples_and_minimum() {
assert_eq!(micros(50000, 13000, 5), 3210);
assert_eq!(micros(50000, 987000, 5), 3210);
for (rate, price, size, expected) in [
(50000, 50, 100, 1250000),
(50000, 30, 100, 1050000),
@@ -101,8 +91,8 @@ mod tests {
(1, 50, 60, 20),
(50000, 0, 1, 0),
] {
assert_eq!(micros(rate, price, size), expected);
assert_eq!(micros(rate, 100 - price, size), expected);
assert_eq!(micros(rate, price * 10000, size), expected);
assert_eq!(micros(rate, (100 - price) * 10000, size), expected);
}
}
}
+37 -1
View File
@@ -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,
+1
View File
@@ -111,6 +111,7 @@ impl Exchange {
| "open_orders"
| "positions"
| "holders"
| "balance"
| "portfolio_value"
| "open_interest"
| "trades"
+25 -4
View File
@@ -16,11 +16,32 @@ pub(crate) fn apply(
request_id: &str,
) -> Result<Value> {
match command {
Command::Fund { account, cents } => {
Command::Fund {
account,
cents,
micros,
} => {
identifier(&account)?;
amount(cents)?;
tx.execute("INSERT INTO accounts VALUES(?,?)", params![account, cents])?;
Ok(json!({"funded":cents}))
let value = match (cents, micros) {
(Some(c), None) => {
amount(c)?;
c * 10000
}
(None, Some(m)) if (1..=10_000_000_000_000).contains(&m) => m,
_ => anyhow::bail!("fund requires exactly one valid amount in cents or micros"),
};
tx.execute(
"INSERT INTO accounts VALUES(?,?)",
params![account, value / 10000],
)?;
if value % 10000 != 0 {
ledger::cash_micros(tx, &account, value % 10000)?;
}
let mut receipt = json!({"funded":value/10000});
if micros.is_some() {
receipt["funded_micros"] = json!(value);
}
Ok(receipt)
}
Command::Event(event) => event.save(tx),
Command::List {
+2 -1
View File
@@ -70,7 +70,8 @@ impl MinimumSize {
// Whole shares are the simulator's executable quantity unit. The
// submitted cash cap includes the taker fee at the protection price.
let qty = (self.0 + SCALE - 1) / SCALE;
let required = qty * max_price * 10000 + crate::fees::micros(fee_rate, max_price, qty);
let required =
qty * max_price * 10000 + crate::fees::micros(fee_rate, max_price * 10000, qty);
ensure!(
cents * 10000 >= required,
"cash budget at protection price is below min_order_size of {} shares",