Apply per-market taker fees to cash budgets, fills and account activity

This commit is contained in:
2026-12-03 05:52:39 +08:00
parent f72d0fe602
commit d01ab8f15c
17 changed files with 312 additions and 36 deletions
+3 -2
View File
@@ -44,7 +44,8 @@ impl Filter {
let sql = format!(
"SELECT seq,market,outcome,side,price,quantity,remaining,status,
(SELECT expiration FROM order_deadlines d WHERE d.seq=orders.seq),
b.amount_cents,b.spent_cents FROM orders LEFT JOIN budget_buys b ON b.order_seq=orders.seq
b.amount_cents,b.spent_cents,
(SELECT COALESCE(SUM(fee_micros),0) FROM execution_fees WHERE taker_order=orders.seq) FROM orders LEFT JOIN budget_buys b ON b.order_seq=orders.seq
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"
);
@@ -77,7 +78,7 @@ impl Filter {
"price_micros":row.get::<_,i64>(4)?*10000,"original_size":quantity,
"size_matched":quantity-remaining,"open_size":if status=="live"{remaining}else{0},
"status":status,"expiration":row.get::<_,Option<i64>>(8)?,
"amount_cents":row.get::<_,Option<i64>>(9)?,"spent_cents":row.get::<_,Option<i64>>(10)?}),
"amount_cents":row.get::<_,Option<i64>>(9)?,"spent_cents":row.get::<_,Option<i64>>(10)?,"fee_micros":row.get::<_,i64>(11)?}),
);
last_id = Some(id);
}
+1 -1
View File
@@ -64,7 +64,7 @@ impl Filter {
json!({"execution":execution,"order":order,"market":market,"outcome":outcome,
"asset_id":assets::id(&market,&outcome),"side":r.get::<_,String>(4)?,
"kind":r.get::<_,String>(5)?,"price_micros":price*10000,"size":size,
"gross_cents":price*size,"at_ms":r.get::<_,Option<i64>>(8)?,
"gross_cents":price*size,"fee_micros":r.get::<_,i64>(10)?,"at_ms":r.get::<_,Option<i64>>(8)?,
"role":r.get::<_,Option<String>>(9)?}),
);
last = Some((execution, order));
+2 -1
View File
@@ -1,6 +1,7 @@
SELECT l.execution,l.order_seq,l.market,l.outcome,l.side,l.kind,l.price,l.quantity,l.at_ms,
CASE WHEN c.execution IS NULL THEN NULL WHEN c.taker_order IS NULL THEN 'auction'
WHEN c.taker_order=l.order_seq THEN 'taker' ELSE 'maker' END
WHEN c.taker_order=l.order_seq THEN 'taker' ELSE 'maker' END,
COALESCE((SELECT fee_micros FROM execution_fees WHERE execution=l.execution AND taker_order=l.order_seq),0)
FROM wallet_trade_legs l LEFT JOIN execution_context c ON c.execution=l.execution
WHERE l.account=?1 AND (?2 IS NULL OR l.market=?2) AND (?3 IS NULL OR l.outcome=?3)
AND (?4 IS NULL OR l.order_seq=?4) AND (l.execution,l.order_seq)<(?5,?6)
+3 -1
View File
@@ -104,9 +104,11 @@ impl Filter {
.as_deref()
.zip(outcome.as_deref())
.map(|(m, o)| assets::id(m, o));
let fee: i64 = r.get(14)?;
let cash: i64 = r.get(9)?;
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":r.get::<_,i64>(9)?,
"shares":r.get::<_,Option<i64>>(8)?,"cash_delta_cents":cash,"fee_micros":fee,"net_cash_delta_micros":i128::from(cash)*10000-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 {
+2 -1
View File
@@ -6,7 +6,8 @@ WITH activity(source,seq,leg,at_ms,kind,market,group_id,shares,cash_delta,reques
quantity*price*CASE side WHEN 'buy' THEN -1 ELSE 1 END,NULL,outcome,side,price
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
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)
FROM activity
WHERE (?2 IS NULL OR market=?2)
AND (?3 IS NULL OR kind IN (SELECT value FROM json_each(?3)))
+2 -1
View File
@@ -18,7 +18,7 @@ pub(crate) fn outcomes(market: &str, yes: &str, no: &str) -> Value {
pub(crate) fn market_assets(db: &Connection, market: &str) -> Result<Value> {
identifier(market)?;
let detail = db.query_row(
let mut detail = db.query_row(
"SELECT COALESCE(s.yes_label,g.yes_label,CASE WHEN t.market IS NULL THEN 'YES' ELSE 'Up' END),
COALESCE(s.no_label,g.no_label,CASE WHEN t.market IS NULL THEN 'NO' ELSE 'Down' END),m.phase,a.role,a.name
FROM markets m LEFT JOIN sports_markets s ON s.market=m.id LEFT JOIN topic_markets g ON g.market=m.id LEFT JOIN twap_markets t ON t.market=m.id LEFT JOIN augmented_outcomes a ON a.market=m.id WHERE m.id=?1",
@@ -34,6 +34,7 @@ pub(crate) fn market_assets(db: &Connection, market: &str) -> Result<Value> {
Ok(detail)
},
)?;
detail["taker_fee_rate_ppm"] = json!(crate::fees::rate(db, market)?);
Ok(detail)
}
+45 -13
View File
@@ -25,10 +25,15 @@ pub(crate) struct ShareExecution {
pub filled: i64,
pub status: String,
pub gross_cents: i64,
pub fee_micros: i64,
}
impl ShareExecution {
pub fn receipt(&self) -> Value {
json!({"order":self.seq,"filled":self.filled,"status":self.status})
let mut receipt = json!({"order":self.seq,"filled":self.filled,"status":self.status});
if self.fee_micros > 0 {
receipt["fee_micros"] = json!(self.fee_micros);
}
receipt
}
}
@@ -94,6 +99,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
)?;
}
let mut gross = 0;
let mut fee_micros = 0;
if stage == "continuous" {
let incoming = Order {
seq,
@@ -120,7 +126,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
"FAK has no matching liquidity"
);
gross = gross_cents(&fills);
settle(tx, &market, &outcome, fills, Some(Taker::Limit(seq)))?;
fee_micros = settle(tx, &market, &outcome, fills, Some(Taker::Limit(seq)))?;
}
let (remaining, mut status): (i64, String) = tx.query_row(
"SELECT remaining,status FROM orders WHERE seq=?",
@@ -131,7 +137,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)?;
Ok(ShareExecution {
fee_micros,
seq,
filled: qty - remaining,
status,
@@ -175,16 +183,19 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
params![account, market, outcome, max_price],
)?;
let seq = tx.last_insert_rowid();
let fills = books
let mut fills = books
.get(&market, &outcome)
.map(|b| b.match_budget_buy(seq, max_price, amount_cents))
.unwrap_or_default();
let rate = crate::fees::rate(tx, &market)?;
crate::fees::fit_budget(rate, &mut fills, amount_cents);
ensure!(!fills.is_empty(), "no affordable liquidity");
let quantity: i64 = fills.iter().map(|f| f.quantity).sum();
let spent = gross_cents(&fills);
let unspent = amount_cents - spent;
let gross_remainder = amount_cents - spent;
let unspent_micros = gross_remainder * 10000 - crate::fees::total(rate, &fills);
ensure!(
tif != TimeInForce::Fok || unspent == 0,
tif != TimeInForce::Fok || unspent_micros == 0,
"FOK cannot fill the entire cash amount"
);
tx.execute(
@@ -195,17 +206,22 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
"INSERT INTO budget_buys(order_seq,amount_cents,spent_cents) VALUES(?,?,?)",
params![seq, amount_cents, spent],
)?;
settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?;
ledger::cash(tx, &account, unspent)?;
let status = if unspent == 0 {
let fee = settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?;
ledger::cash(tx, &account, gross_remainder)?;
crate::fees::debit(tx, &account, fee)?;
let status = if unspent_micros == 0 {
"filled"
} else {
tx.execute("UPDATE orders SET status='cancelled' WHERE seq=?", [seq])?;
"cancelled"
};
Ok(
json!({"order":seq,"status":status,"filled":quantity,"amount_cents":amount_cents,"spent_cents":spent,"unspent_cents":unspent}),
)
let mut receipt = json!({"order":seq,"status":status,"filled":quantity,"amount_cents":amount_cents,"spent_cents":spent,"unspent_cents":unspent_micros/10000});
if fee > 0 {
receipt["fee_micros"] = json!(fee);
receipt["unspent_micros"] = json!(unspent_micros);
receipt["total_spent_micros"] = json!(spent * 10000 + fee);
}
Ok(receipt)
}
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -271,7 +287,13 @@ pub(crate) fn settle(
outcome: &str,
fills: Vec<Fill>,
taker: Option<Taker>,
) -> Result<()> {
) -> Result<i64> {
let rate = if taker.is_some() && !fills.is_empty() {
crate::fees::rate(tx, market)?
} else {
0
};
let mut fees = 0;
for f in fills {
let first = book_leg(tx, market, outcome, &f, f.bid, taker)?;
let second = book_leg(tx, market, outcome, &f, f.ask, taker)?;
@@ -322,11 +344,21 @@ pub(crate) fn settle(
"INSERT INTO execution_context(execution,taker_order) VALUES(?,?)",
params![execution, taker.map(Taker::seq)],
)?;
if let Some(taker) = taker {
let fee = crate::fees::micros(rate, f.price, f.quantity);
if fee > 0 {
tx.execute(
"INSERT INTO execution_fees VALUES(?,?,?)",
params![execution, taker.seq(), fee],
)?;
fees += fee;
}
}
for seq in [f.bid, f.ask] {
tx.execute("UPDATE orders SET remaining=remaining-?1,status=CASE WHEN remaining=?1 THEN 'filled' ELSE 'live' END WHERE seq=?2",params![f.quantity,seq])?;
}
}
Ok(())
Ok(fees)
}
pub(crate) enum CancelReason {
+1
View File
@@ -11,6 +11,7 @@ pub(crate) enum Command {
List {
market: String,
rules: String,
taker_fee_rate_ppm: Option<i64>,
#[serde(default)]
listing: Option<crate::catalog::Listing>,
resolution: Option<crate::resolution::Policy>,
+28 -12
View File
@@ -76,7 +76,7 @@ impl Request {
let changes = books.changes(tx)?;
books.apply(changes);
// The hypothetical incoming order follows all resting orders in time priority.
let fills = books
let mut fills = books
.get(&market, &outcome)
.map(|b| match side {
Side::Buy => b.match_budget_buy(i64::MAX, limit, requested),
@@ -88,23 +88,39 @@ impl Request {
}),
})
.unwrap_or_default();
let rate = crate::fees::rate(tx, &market)?;
if side == Side::Buy {
crate::fees::fit_budget(rate, &mut fills, requested);
}
let fee = crate::fees::total(rate, &fills);
let shares: i64 = fills.iter().map(|f| f.quantity).sum();
let gross = gross_cents(&fills);
let remainder = requested
- match side {
Side::Buy => gross,
Side::Sell => shares,
};
let remaining_cash = if side == Side::Buy {
(requested - gross) * 10000 - fee
} else {
0
};
let fully_fillable = match side {
Side::Buy => remaining_cash == 0,
Side::Sell => requested == shares,
};
let mut result = json!({"asset_id":assets::id(&market,&outcome),"filled_shares":shares,
"gross_cents":gross,"best_fill_price":fills.first().map(|f|f.price),
"worst_fill_price":fills.last().map(|f|f.price),
"average_price_micros":(gross*10000).checked_div(shares),
"fully_fillable":remainder==0,"executable":shares>0 && (tif==TimeInForce::Fak || remainder==0)});
let key = match side {
Side::Buy => "unspent_cents",
Side::Sell => "unsold_shares",
};
result[key] = json!(remainder);
"fee_micros":fee,"taker_fee_rate_ppm":rate,
"fully_fillable":fully_fillable,"executable":shares>0 && (tif==TimeInForce::Fak || fully_fillable)});
match side {
Side::Buy => {
result["total_spent_micros"] = json!(gross * 10000 + fee);
result["unspent_cents"] = json!(remaining_cash / 10000);
result["unspent_micros"] = json!(remaining_cash);
}
Side::Sell => {
result["net_proceeds_micros"] = json!(gross * 10000 - fee);
result["unsold_shares"] = json!(requested - shares);
}
}
Ok(result)
}
}
+108
View File
@@ -0,0 +1,108 @@
use crate::ledger;
use anyhow::{ensure, Result};
use matching::Fill;
use rusqlite::{params, Connection, Transaction};
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 {
return 0;
}
(((numerator + 50_000) / 100_000) * 10) as i64
}
pub(crate) fn total(rate: i64, fills: &[Fill]) -> i64 {
fills
.iter()
.map(|f| micros(rate, f.price, f.quantity))
.sum()
}
// match_budget_buy supplies FIFO candidates under the gross cap. Stop at
// the first partially affordable maker, including its rounded fee.
pub(crate) fn fit_budget(rate: i64, fills: &mut Vec<Fill>, budget: i64) {
if rate == 0 {
return;
}
let mut remaining = budget * 10000;
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))
};
if cost(f.quantity) <= i128::from(remaining) {
remaining -= cost(f.quantity) as i64;
count += 1;
continue;
}
let (mut lo, mut hi) = (0, f.quantity);
while lo < hi {
let mid = lo + (hi - lo + 1) / 2;
if cost(mid) <= i128::from(remaining) {
lo = mid;
} else {
hi = mid - 1;
}
}
if lo > 0 {
f.quantity = lo;
count += 1;
}
break;
}
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(
"INSERT INTO market_fee_rates VALUES(?,?)",
params![market, rate],
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::micros;
#[test]
fn symmetric_taker_curve_matches_published_examples_and_minimum() {
for (rate, price, size, expected) in [
(50000, 50, 100, 1250000),
(50000, 30, 100, 1050000),
(10000, 50, 100, 250000),
(10000, 30, 100, 210000),
(0, 50, 100, 0),
(1, 50, 39, 0),
(1, 50, 40, 10),
(1, 50, 60, 20),
(50000, 0, 1, 0),
] {
assert_eq!(micros(rate, price, size), expected);
assert_eq!(micros(rate, 100 - price, size), expected);
}
}
}
+3
View File
@@ -6,6 +6,7 @@ mod augmented;
mod catalog;
mod estimate;
mod expiry;
mod fees;
mod holders;
mod twap;
mod validation;
@@ -107,6 +108,8 @@ impl Exchange {
let mut state = Map::new();
for table in [
"accounts",
"cash_remainders",
"execution_fees",
"markets",
"positions",
"orders",
+8
View File
@@ -28,6 +28,7 @@ pub(crate) fn apply(
rules,
listing,
resolution,
taker_fee_rate_ppm,
} => {
identifier(&market)?;
ensure!(!rules.trim().is_empty(), "rules required");
@@ -35,6 +36,9 @@ pub(crate) fn apply(
"INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')",
params![market, rules],
)?;
if let Some(rate) = taker_fee_rate_ppm {
crate::fees::configure(tx, &market, rate)?;
}
if let Some(policy) = resolution {
policy.save(tx, &market)?;
}
@@ -176,6 +180,10 @@ pub(crate) fn apply(
let mut receipt = result.receipt();
receipt["proceeds_cents"] = json!(result.gross_cents);
receipt["unsold_shares"] = json!(qty - result.filled);
if result.fee_micros > 0 {
receipt["net_proceeds_micros"] =
json!(result.gross_cents * 10000 - result.fee_micros);
}
Ok(receipt)
}
Command::MarketBuy {
+12
View File
@@ -233,3 +233,15 @@ WHEN NEW.phase='resolved' AND OLD.phase<>'resolved' BEGIN
INSERT INTO price_settlements(market,winner,at_ms)
VALUES(NEW.id,NEW.winner,CAST(unixepoch('subsec')*1000 AS INTEGER));
END;
CREATE TABLE IF NOT EXISTS market_fee_rates (
market TEXT PRIMARY KEY REFERENCES markets(id), rate_ppm INTEGER NOT NULL CHECK(rate_ppm BETWEEN 0 AND 1000000)
);
CREATE TABLE IF NOT EXISTS cash_remainders (
account TEXT PRIMARY KEY REFERENCES accounts(id), micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 9999)
);
CREATE TABLE IF NOT EXISTS execution_fees (
execution INTEGER PRIMARY KEY REFERENCES execution_context(execution),
taker_order INTEGER NOT NULL REFERENCES orders(seq), fee_micros INTEGER NOT NULL CHECK(fee_micros>0)
);
CREATE INDEX IF NOT EXISTS fees_by_order ON execution_fees(taker_order);