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
+26
View File
@@ -40,6 +40,11 @@ flowchart LR
queries -->|市价预估| estimate["src/estimate.rs"] queries -->|市价预估| estimate["src/estimate.rs"]
estimate -->|同步并读取常驻盘口| cache estimate -->|同步并读取常驻盘口| cache
estimate -->|成交金额| book estimate -->|成交金额| book
estimate -->|含费预算| fees["src/fees.rs"]
book -->|记录吃单手续费并扣款| fees
market -->|上架费率| fees
assets -->|公开费率| fees
fees -->|整分现金及余下微单位| ledger
queries -->|按账户或订单对账| trades["src/account_trades.rs"] queries -->|按账户或订单对账| trades["src/account_trades.rs"]
trades -->|读取两类成交| legsql["src/account_trades.sql"] trades -->|读取两类成交| legsql["src/account_trades.sql"]
trades -->|返回结果资产| assets trades -->|返回结果资产| assets
@@ -531,3 +536,24 @@ sequenceDiagram
end end
E-->>C: 按市场或全站返回估值、已定价小计及缺价份额 E-->>C: 按市场或全站返回估值、已定价小计及缺价份额
``` ```
## 含手续费的成交
```mermaid
sequenceDiagram
participant C as 客户端
participant E as Exchange
participant B as 常驻订单簿
participant D as SQLite
C->>E: estimate 或下单
E->>D: 读取市场费率
E->>B: 按价格和时间取候选成交
E->>E: 逐笔计算吃单费,预算买单截取含费可买的整份
alt 预估
E-->>C: 预期费用、净现金与可执行性
else 下单
E->>D: 同一事务保存成交、费用、持仓及现金余数
D-->>E: 提交成功或全笔回滚
E-->>C: 返回成交回执或错误
end
```
+3 -2
View File
@@ -44,7 +44,8 @@ impl Filter {
let sql = format!( let sql = format!(
"SELECT seq,market,outcome,side,price,quantity,remaining,status, "SELECT seq,market,outcome,side,price,quantity,remaining,status,
(SELECT expiration FROM order_deadlines d WHERE d.seq=orders.seq), (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) 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" 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, "price_micros":row.get::<_,i64>(4)?*10000,"original_size":quantity,
"size_matched":quantity-remaining,"open_size":if status=="live"{remaining}else{0}, "size_matched":quantity-remaining,"open_size":if status=="live"{remaining}else{0},
"status":status,"expiration":row.get::<_,Option<i64>>(8)?, "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); last_id = Some(id);
} }
+1 -1
View File
@@ -64,7 +64,7 @@ impl Filter {
json!({"execution":execution,"order":order,"market":market,"outcome":outcome, json!({"execution":execution,"order":order,"market":market,"outcome":outcome,
"asset_id":assets::id(&market,&outcome),"side":r.get::<_,String>(4)?, "asset_id":assets::id(&market,&outcome),"side":r.get::<_,String>(4)?,
"kind":r.get::<_,String>(5)?,"price_micros":price*10000,"size":size, "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)?}), "role":r.get::<_,Option<String>>(9)?}),
); );
last = Some((execution, order)); 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, 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' 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 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) 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) 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() .as_deref()
.zip(outcome.as_deref()) .zip(outcome.as_deref())
.map(|(m, o)| assets::id(m, o)); .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)?, 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, "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), "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)})); "request_id":r.get::<_,Option<String>>(10)?,"execution":(source==1).then_some(seq),"order":(source==1).then_some(leg)}));
last = Some(Cursor { 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 quantity*price*CASE side WHEN 'buy' THEN -1 ELSE 1 END,NULL,outcome,side,price
FROM wallet_trade_legs WHERE account=?1 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 FROM activity
WHERE (?2 IS NULL OR market=?2) WHERE (?2 IS NULL OR market=?2)
AND (?3 IS NULL OR kind IN (SELECT value FROM json_each(?3))) 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> { pub(crate) fn market_assets(db: &Connection, market: &str) -> Result<Value> {
identifier(market)?; 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), "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 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", 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) Ok(detail)
}, },
)?; )?;
detail["taker_fee_rate_ppm"] = json!(crate::fees::rate(db, market)?);
Ok(detail) Ok(detail)
} }
+45 -13
View File
@@ -25,10 +25,15 @@ pub(crate) struct ShareExecution {
pub filled: i64, pub filled: i64,
pub status: String, pub status: String,
pub gross_cents: i64, pub gross_cents: i64,
pub fee_micros: i64,
} }
impl ShareExecution { impl ShareExecution {
pub fn receipt(&self) -> Value { 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 gross = 0;
let mut fee_micros = 0;
if stage == "continuous" { if stage == "continuous" {
let incoming = Order { let incoming = Order {
seq, seq,
@@ -120,7 +126,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
"FAK has no matching liquidity" "FAK has no matching liquidity"
); );
gross = gross_cents(&fills); 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( let (remaining, mut status): (i64, String) = tx.query_row(
"SELECT remaining,status FROM orders WHERE seq=?", "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)?; release(tx, seq, &account, CancelReason::Cancelled)?;
status = "cancelled".into(); status = "cancelled".into();
} }
crate::fees::debit(tx, &account, fee_micros)?;
Ok(ShareExecution { Ok(ShareExecution {
fee_micros,
seq, seq,
filled: qty - remaining, filled: qty - remaining,
status, status,
@@ -175,16 +183,19 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
params![account, market, outcome, max_price], params![account, market, outcome, max_price],
)?; )?;
let seq = tx.last_insert_rowid(); let seq = tx.last_insert_rowid();
let fills = books let mut fills = books
.get(&market, &outcome) .get(&market, &outcome)
.map(|b| b.match_budget_buy(seq, max_price, amount_cents)) .map(|b| b.match_budget_buy(seq, max_price, amount_cents))
.unwrap_or_default(); .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"); ensure!(!fills.is_empty(), "no affordable liquidity");
let quantity: i64 = fills.iter().map(|f| f.quantity).sum(); let quantity: i64 = fills.iter().map(|f| f.quantity).sum();
let spent = gross_cents(&fills); 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!( ensure!(
tif != TimeInForce::Fok || unspent == 0, tif != TimeInForce::Fok || unspent_micros == 0,
"FOK cannot fill the entire cash amount" "FOK cannot fill the entire cash amount"
); );
tx.execute( 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(?,?,?)", "INSERT INTO budget_buys(order_seq,amount_cents,spent_cents) VALUES(?,?,?)",
params![seq, amount_cents, spent], params![seq, amount_cents, spent],
)?; )?;
settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?; let fee = settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?;
ledger::cash(tx, &account, unspent)?; ledger::cash(tx, &account, gross_remainder)?;
let status = if unspent == 0 { crate::fees::debit(tx, &account, fee)?;
let status = if unspent_micros == 0 {
"filled" "filled"
} else { } else {
tx.execute("UPDATE orders SET status='cancelled' WHERE seq=?", [seq])?; tx.execute("UPDATE orders SET status='cancelled' WHERE seq=?", [seq])?;
"cancelled" "cancelled"
}; };
Ok( let mut receipt = json!({"order":seq,"status":status,"filled":quantity,"amount_cents":amount_cents,"spent_cents":spent,"unspent_cents":unspent_micros/10000});
json!({"order":seq,"status":status,"filled":quantity,"amount_cents":amount_cents,"spent_cents":spent,"unspent_cents":unspent}), 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)] #[derive(Clone, Copy, PartialEq, Eq)]
@@ -271,7 +287,13 @@ pub(crate) fn settle(
outcome: &str, outcome: &str,
fills: Vec<Fill>, fills: Vec<Fill>,
taker: Option<Taker>, 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 { for f in fills {
let first = book_leg(tx, market, outcome, &f, f.bid, taker)?; let first = book_leg(tx, market, outcome, &f, f.bid, taker)?;
let second = book_leg(tx, market, outcome, &f, f.ask, 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(?,?)", "INSERT INTO execution_context(execution,taker_order) VALUES(?,?)",
params![execution, taker.map(Taker::seq)], 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] { 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])?; 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 { pub(crate) enum CancelReason {
+1
View File
@@ -11,6 +11,7 @@ pub(crate) enum Command {
List { List {
market: String, market: String,
rules: String, rules: String,
taker_fee_rate_ppm: Option<i64>,
#[serde(default)] #[serde(default)]
listing: Option<crate::catalog::Listing>, listing: Option<crate::catalog::Listing>,
resolution: Option<crate::resolution::Policy>, resolution: Option<crate::resolution::Policy>,
+28 -12
View File
@@ -76,7 +76,7 @@ impl Request {
let changes = books.changes(tx)?; let changes = books.changes(tx)?;
books.apply(changes); books.apply(changes);
// The hypothetical incoming order follows all resting orders in time priority. // The hypothetical incoming order follows all resting orders in time priority.
let fills = books let mut fills = books
.get(&market, &outcome) .get(&market, &outcome)
.map(|b| match side { .map(|b| match side {
Side::Buy => b.match_budget_buy(i64::MAX, limit, requested), Side::Buy => b.match_budget_buy(i64::MAX, limit, requested),
@@ -88,23 +88,39 @@ impl Request {
}), }),
}) })
.unwrap_or_default(); .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 shares: i64 = fills.iter().map(|f| f.quantity).sum();
let gross = gross_cents(&fills); let gross = gross_cents(&fills);
let remainder = requested let remaining_cash = if side == Side::Buy {
- match side { (requested - gross) * 10000 - fee
Side::Buy => gross, } else {
Side::Sell => shares, 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, 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), "gross_cents":gross,"best_fill_price":fills.first().map(|f|f.price),
"worst_fill_price":fills.last().map(|f|f.price), "worst_fill_price":fills.last().map(|f|f.price),
"average_price_micros":(gross*10000).checked_div(shares), "average_price_micros":(gross*10000).checked_div(shares),
"fully_fillable":remainder==0,"executable":shares>0 && (tif==TimeInForce::Fak || remainder==0)}); "fee_micros":fee,"taker_fee_rate_ppm":rate,
let key = match side { "fully_fillable":fully_fillable,"executable":shares>0 && (tif==TimeInForce::Fak || fully_fillable)});
Side::Buy => "unspent_cents", match side {
Side::Sell => "unsold_shares", Side::Buy => {
}; result["total_spent_micros"] = json!(gross * 10000 + fee);
result[key] = json!(remainder); 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) 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 catalog;
mod estimate; mod estimate;
mod expiry; mod expiry;
mod fees;
mod holders; mod holders;
mod twap; mod twap;
mod validation; mod validation;
@@ -107,6 +108,8 @@ impl Exchange {
let mut state = Map::new(); let mut state = Map::new();
for table in [ for table in [
"accounts", "accounts",
"cash_remainders",
"execution_fees",
"markets", "markets",
"positions", "positions",
"orders", "orders",
+8
View File
@@ -28,6 +28,7 @@ pub(crate) fn apply(
rules, rules,
listing, listing,
resolution, resolution,
taker_fee_rate_ppm,
} => { } => {
identifier(&market)?; identifier(&market)?;
ensure!(!rules.trim().is_empty(), "rules required"); ensure!(!rules.trim().is_empty(), "rules required");
@@ -35,6 +36,9 @@ pub(crate) fn apply(
"INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')", "INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')",
params![market, rules], params![market, rules],
)?; )?;
if let Some(rate) = taker_fee_rate_ppm {
crate::fees::configure(tx, &market, rate)?;
}
if let Some(policy) = resolution { if let Some(policy) = resolution {
policy.save(tx, &market)?; policy.save(tx, &market)?;
} }
@@ -176,6 +180,10 @@ pub(crate) fn apply(
let mut receipt = result.receipt(); let mut receipt = result.receipt();
receipt["proceeds_cents"] = json!(result.gross_cents); receipt["proceeds_cents"] = json!(result.gross_cents);
receipt["unsold_shares"] = json!(qty - result.filled); 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) Ok(receipt)
} }
Command::MarketBuy { 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) INSERT INTO price_settlements(market,winner,at_ms)
VALUES(NEW.id,NEW.winner,CAST(unixepoch('subsec')*1000 AS INTEGER)); VALUES(NEW.id,NEW.winner,CAST(unixepoch('subsec')*1000 AS INTEGER));
END; 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);
+46
View File
@@ -1861,3 +1861,49 @@ fn priced_interest_follows_outstanding_tokens_through_transfer_merge_and_redempt
json!([]) json!([])
); );
} }
#[test]
fn fees_follow_taker_cash_budget_and_net_sale_proceeds() {
let dir = tempdir().unwrap();
let path = dir.path().join("fees.db");
let mut e = Exchange::open(&path).unwrap();
for line in include_str!("../../../docs/examples/fees.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
if cmd["op"] == "market_buy" {
e.execute(json!({"op":"fund","id":"poor","account":"poor","cents":5000}))
.unwrap();
let before = state(&mut e);
assert!(e.execute(json!({"op":"order","id":"unfunded-fee","market":"cup","outcome":"YES","side":"buy","price":50,"qty":100,"account":"poor"})).is_err());
assert_eq!(state(&mut e), before);
}
let reply = e.execute(cmd.clone()).unwrap();
match cmd["op"].as_str().unwrap() {
"estimate" if cmd["amount_cents"] == 5000 => assert_eq!(reply["filled_shares"], 97),
"estimate" => assert_eq!(reply["fee_micros"], 1250000),
"market_buy" => {
assert_eq!(reply["total_spent_micros"], 51250000);
assert_eq!(reply["fee_micros"], 1250000);
drop(e);
e = Exchange::open(&path).unwrap();
assert_eq!(e.execute(cmd).unwrap(), reply);
}
"market_sell" => {
assert_eq!(reply["fee_micros"], 10500);
assert_eq!(reply["net_proceeds_micros"], 289500);
}
_ => {}
}
}
let s = state(&mut e);
assert_eq!(s["accounts"][1]["cash"], 903);
assert_eq!(s["cash_remainders"][0]["micros"], 9500);
assert_eq!(s["execution_fees"].as_array().unwrap().len(), 2);
let leg = e
.execute(json!({"op":"trades","account":"alice","market":"cup"}))
.unwrap();
assert!(leg["trades"]
.as_array()
.unwrap()
.iter()
.all(|r| r["fee_micros"] == 0));
}
+12
View File
@@ -0,0 +1,12 @@
{"op":"list","id":"m","market":"cup","rules":"按模拟杯赛结果结算","taker_fee_rate_ppm":50000}
{"op":"fund","id":"a","account":"alice","cents":15000}
{"op":"fund","id":"b","account":"bob","cents":6000}
{"op":"split","id":"split","market":"cup","account":"alice","qty":100}
{"op":"open","id":"open","market":"cup"}
{"op":"order","id":"ask","market":"cup","outcome":"YES","account":"alice","side":"sell","price":50,"qty":100}
{"op":"estimate","market":"cup","outcome":"YES","side":"buy","amount_cents":5000}
{"op":"estimate","market":"cup","outcome":"YES","side":"buy","amount_cents":5125}
{"op":"market_buy","id":"buy","market":"cup","outcome":"YES","account":"bob","amount_cents":5125,"max_price":50,"tif":"FOK"}
{"op":"order","id":"bid","market":"cup","outcome":"YES","account":"alice","side":"buy","price":30,"qty":1}
{"op":"market_sell","id":"sell","market":"cup","outcome":"YES","account":"bob","qty":1,"min_price":30}
{"op":"activity","account":"bob","types":["TRADE"]}
+10 -4
View File
@@ -35,7 +35,7 @@
NO 买入价 40 分在 YES 盘口投影为 60 分卖价。每笔订单按投影价和原受理序号进入两个视图,提交新单只遍历一个视图。最优对手既可为普通卖单,也可为已经预留资金的 NO 买单。两笔买单成交时,每对共存入 100 分抵押;两笔互补卖单成交时,每对释放 100 分并按各自成交价入账。同结果转手继续写 fills,互补成交写 paired_fills,一次成交共享一个执行序号,两侧的历史价格分别记录其成交金额。state 返回两种流水。重启以原订单和余量恢复两个视图。 NO 买入价 40 分在 YES 盘口投影为 60 分卖价。每笔订单按投影价和原受理序号进入两个视图,提交新单只遍历一个视图。最优对手既可为普通卖单,也可为已经预留资金的 NO 买单。两笔买单成交时,每对共存入 100 分抵押;两笔互补卖单成交时,每对释放 100 分并按各自成交价入账。同结果转手继续写 fills,互补成交写 paired_fills,一次成交共享一个执行序号,两侧的历史价格分别记录其成交金额。state 返回两种流水。重启以原订单和余量恢复两个视图。
这是本地无费用模型。链上合约的签名、费用及执行最终性另行核对。批量开盘采用本地统一价规则。[官方价格发现](https://docs.polymarket.com/concepts/prices-orderbook.md) · [CTF Exchange 的三种成交方式](https://github.com/Polymarket/ctf-exchange/blob/main/docs/Overview.md) 该例沿用默认的零费率。链上合约的签名、费用及执行最终性另行核对。批量开盘采用本地统一价规则。[官方价格发现](https://docs.polymarket.com/concepts/prices-orderbook.md) · [CTF Exchange 的三种成交方式](https://github.com/Polymarket/ctf-exchange/blob/main/docs/Overview.md)
## 分档深度样例 ## 分档深度样例
@@ -79,7 +79,7 @@ Polymarket 的 CTF 市场使用结果 token ID,Protocol V2 市场使用结果
发送 `{"op":"trades","account":"alice","market":"e","limit":100}`。传 order 可只看指定原单,传 asset_id 可限定结果。每一行对应一次执行中该账户的一份原委托,含 execution、order、side、size、price_micros、gross_cents 和 role;gross_cents 为正数,买入表示支出、卖出表示收入。按执行号、原单号从新到旧排列;续页时保持筛选条件,将 next_after 原样作为 after。相同执行中若账户持有两笔原委托,两个记录共用执行号。只统计某个订单时把这些记录的 size 相加,可与 open_orders 的 size_matched 对账。 发送 `{"op":"trades","account":"alice","market":"e","limit":100}`。传 order 可只看指定原单,传 asset_id 可限定结果。每一行对应一次执行中该账户的一份原委托,含 execution、order、side、size、price_micros、gross_cents 和 role;gross_cents 为正数,买入表示支出、卖出表示收入。按执行号、原单号从新到旧排列;续页时保持筛选条件,将 next_after 原样作为 after。相同执行中若账户持有两笔原委托,两个记录共用执行号。只统计某个订单时把这些记录的 size 相加,可与 open_orders 的 size_matched 对账。
例如 NO 买单在 40 分成交 10 份,与另一账户的 YES 买单成对发行时,NO 的 gross_cents 为 400,YES 为 600。同结果转手标记 transfer,两笔互补买单标记 mint,两笔互补卖单标记 merge。连续交易记录 maker 或 taker,开盘竞价记录 auction;旧成交缺少角色或时间时返回 null。单独 split、merge、redeem 的钱包活动、手续费、链上交易哈希与结算状态仍待接入。模拟器按原订单分别列出成交;官方接口可在一项成交内嵌多个 maker 订单。[Polymarket 账户成交查询](https://docs.polymarket.com/trading/manage-orders.md) 例如 NO 买单在 40 分成交 10 份,与另一账户的 YES 买单成对发行时,NO 的 gross_cents 为 400,YES 为 600。同结果转手标记 transfer,两笔互补买单标记 mint,两笔互补卖单标记 merge。连续交易记录 maker 或 taker,开盘竞价记录 auction;旧成交缺少角色或时间时返回 null。钱包活动可查 split、merge、redeem 和实际吃单费;链上交易哈希与结算状态仍待对照。模拟器按原订单分别列出成交;官方接口可在一项成交内嵌多个 maker 订单。[Polymarket 账户成交查询](https://docs.polymarket.com/trading/manage-orders.md)
## 提案与争议 ## 提案与争议
@@ -107,7 +107,7 @@ Polymarket 的 CTF 市场使用结果 token ID,Protocol V2 市场使用结果
`{"op":"market_buy","id":"cash-buy-1","asset_id":"eb:YES:e","account":"buyer","amount_cents":170,"max_price":50,"tif":"FAK"}` 在连续交易阶段锁定 170 分预算。若最优卖单为 35 分两份,下一档为 NO 买单映射出的 45 分三份,则成交四份,实付 160 分,退回 10 分。订单可查到原始金额和实付金额;精确查询中的 original_size 是本地换算后的成交份数。操作接受现有 market / outcome 寻址,max_price 为每份最高可接受分价。FAK 为本地默认值;剩余预算即时撤销,有余款的回执 status 为 cancelled,filled 保留实际成交份数。 `{"op":"market_buy","id":"cash-buy-1","asset_id":"eb:YES:e","account":"buyer","amount_cents":170,"max_price":50,"tif":"FAK"}` 在连续交易阶段锁定 170 分预算。若最优卖单为 35 分两份,下一档为 NO 买单映射出的 45 分三份,则成交四份,实付 160 分,退回 10 分。订单可查到原始金额和实付金额;精确查询中的 original_size 是本地换算后的成交份数。操作接受现有 market / outcome 寻址,max_price 为每份最高可接受分价。FAK 为本地默认值;剩余预算即时撤销,有余款的回执 status 为 cancelled,filled 保留实际成交份数。
FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高价、没有可负担份额、账户可用现金不足以预留全部预算时也拒绝。买方按预算预留,遇较优成交价时只产生一次未花金额退款。当前撮合单位为整数份和分,外场支持小数份额及签名金额舍入;费用和实际外场零碎余量行为仍待对照。测试入口为 cash_buy_reconciles_direct_and_complementary_depth_with_an_exact_budget。[Polymarket 市价单与金额口径](https://docs.polymarket.com/trading/place-orders.md) FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高价、没有可负担份额、账户可用现金不足以预留全部预算时也拒绝。买方按预算预留,遇较优成交价时只产生一次未花金额退款。当前撮合单位为整数份和整分价格,手续费另按五位小数计算。外场小数份额、签名舍入和实际零碎余量行为仍待对照。测试入口为 cash_buy_reconciles_direct_and_complementary_depth_with_an_exact_budget。[Polymarket 市价单与金额口径](https://docs.polymarket.com/trading/place-orders.md)
## 市价保护价与预估 ## 市价保护价与预估
@@ -193,4 +193,10 @@ FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高
[可重放样例](examples/open-interest.jsonl)中,Alice 拆出 YES 和 NO 各 10 份,再将两份 YES 卖给 Bob。转手后仍有 20 份流通。当 YES 中点为 0.57、NO 中点为 0.43,未平仓量为 10.00 模拟美元。Alice 合并三对后剩下 14 份、价值 7.00。YES 获胜后 Alice 先赎回,Bob 的两份仍值 2.00,直到他也赎回才归零。 [可重放样例](examples/open-interest.jsonl)中,Alice 拆出 YES 和 NO 各 10 份,再将两份 YES 卖给 Bob。转手后仍有 20 份流通。当 YES 中点为 0.57、NO 中点为 0.43,未平仓量为 10.00 模拟美元。Alice 合并三对后剩下 14 份、价值 7.00。YES 获胜后 Alice 先赎回,Bob 的两份仍值 2.00,直到他也赎回才归零。
查询 `{"op":"open_interest","market":["cup","other"]}` 或 `{"op":"open_interest"}`。value 为模拟美元,value_micros 为整数微单位。未成交卖单的预留份额仍归原持有人;抵押账户、互斥组现金准备金及挂买单的冻结金额不额外计入。已有持仓但缺价时,响应给出 unpriced_shares 和 priced_value_micros,value 为 null。空盘有明确的零值。本地使用持仓查询的估值来源,查询范围是本地已上架且公开的市场,包括已裁决的待赎回份额。当前费用接收方份额为零;生产费用归属、定价源及 active/archived 的可见性需要另行核对。 查询 `{"op":"open_interest","market":["cup","other"]}` 或 `{"op":"open_interest"}`。value 为模拟美元,value_micros 为整数微单位。未成交卖单的预留份额仍归原持有人;抵押账户、互斥组现金准备金及挂买单的冻结金额不额外计入。已有持仓但缺价时,响应给出 unpriced_shares 和 priced_value_micros,value 为 null。空盘有明确的零值。本地使用持仓查询的估值来源,查询范围是本地已上架且公开的市场,包括已裁决的待赎回份额。本地 V2 手续费以现金入账,费用接收方份额为零;生产费用归属、定价源及 active/archived 的可见性需要另行核对。
## 吃单费用与现金精度
上架时可显式配置 taker_fee_rate_ppm。50000 表示 0.05,10000 表示 0.01。未设置及旧市场沿用零费率。当前实现指数为 1,只向连续交易的吃单方收取协议费用。每笔按成交份额 × 费率 × 结果价格 × (1 − 结果价格) 计价;买单从现金另付,卖单从现金所得中扣除。所有成交价使用成交记录中的实际价格。低于 0.00001 模拟美元的单笔费用计零,其余就近取五位小数,正中取上。逐笔舍入和并列值取上的行为仍需与生产对账。[官方公式及算例](https://docs.polymarket.com/trading/fees.md) · [市场费率、指数和收取方配置](https://docs.polymarket.com/market-data/market-details.md) · [V2 合约买卖双方抵押币扣款](https://github.com/Polymarket/ctf-exchange-v2/blob/main/src/exchange/mixins/Trading.sol)
[可重放样例](examples/fees.jsonl)中,100 份 × 0.50,费率 0.05 时收 1.25。现金预算 50.00 仅能买 97 整份;预算 51.25 恰好能买 100 份。再以 0.30 卖 1 份时费用为 0.01050,净收入 0.28950。estimate 的 fee_micros 是预估深度中各笔费用之和,executable 表示整单能否按所选 TIF 执行;失败回滚整笔交易。回执、账户订单、成交与活动可核对实际费用。活动的 cash_delta_cents 记录毛现金变动,net_cash_delta_micros 扣除费用。state 中某账户可用现金的微单位值等于 accounts.cash × 10000 加该账户 cash_remainders.micros(无记录按零);execution_fees 为协议应收账本。完整现金预算含手续费,spent_cents 保留毛成交额。旧市场与本地开盘集合竞价均不收取此费。生产市场费率更新、返佣、builder 附加费与真实收费记录仍待对照。