Reconcile precise collateral funding, fee debits and available cash
This commit is contained in:
@@ -56,7 +56,8 @@ flowchart LR
|
|||||||
book -->|记录吃单手续费并扣款| fees
|
book -->|记录吃单手续费并扣款| fees
|
||||||
market -->|上架费率| fees
|
market -->|上架费率| fees
|
||||||
assets -->|公开费率| fees
|
assets -->|公开费率| fees
|
||||||
fees -->|整分现金及余下微单位| ledger
|
queries -->|可用和挂买预留的现金| ledger
|
||||||
|
book -->|精确扣费或退回含费余款| 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
|
||||||
@@ -627,3 +628,22 @@ sequenceDiagram
|
|||||||
Q->>Q: 反推出 NO 报价,按请求方向选择对手价
|
Q->>Q: 反推出 NO 报价,按请求方向选择对手价
|
||||||
Q-->>C: 按资产与方向返回价格,无对手报 null
|
Q-->>C: 按资产与方向返回价格,无对手报 null
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 现金余额与费用
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
participant C as 客户端
|
||||||
|
participant E as Exchange
|
||||||
|
participant D as SQLite 账本
|
||||||
|
C->>E: fund 使用 cents 或 micros 建立模拟账户
|
||||||
|
E->>D: 同一事务保存整分、零头及幂等回执
|
||||||
|
C->>E: 买入限价单
|
||||||
|
E->>D: 预留本金,按成交价结算并扣除微单位手续费
|
||||||
|
alt 可用余额不足
|
||||||
|
E->>D: 回滚订单、成交与资金变动
|
||||||
|
end
|
||||||
|
C->>E: balance 指定账户
|
||||||
|
E->>D: 同一快照读取可用金额及有效买单的预留金额
|
||||||
|
E-->>C: available_micros、reserved_micros、total_cash_micros
|
||||||
|
```
|
||||||
|
|||||||
@@ -106,9 +106,11 @@ impl Filter {
|
|||||||
.map(|(m, o)| assets::id(m, o));
|
.map(|(m, o)| assets::id(m, o));
|
||||||
let fee: i64 = r.get(14)?;
|
let fee: i64 = r.get(14)?;
|
||||||
let cash: i64 = r.get(9)?;
|
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)?,
|
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":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),
|
"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 {
|
||||||
|
|||||||
@@ -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
|
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)
|
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
|
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)))
|
||||||
|
|||||||
@@ -143,7 +143,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)?;
|
if fee_micros > 0 {
|
||||||
|
ledger::cash_micros(tx, &account, -fee_micros)?;
|
||||||
|
}
|
||||||
Ok(ShareExecution {
|
Ok(ShareExecution {
|
||||||
fee_micros,
|
fee_micros,
|
||||||
seq,
|
seq,
|
||||||
@@ -219,8 +221,7 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
|
|||||||
params![seq, amount_cents, spent],
|
params![seq, amount_cents, spent],
|
||||||
)?;
|
)?;
|
||||||
let fee = settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?;
|
let fee = settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?;
|
||||||
ledger::cash(tx, &account, gross_remainder)?;
|
ledger::cash_micros(tx, &account, gross_remainder * 10000 - fee)?;
|
||||||
crate::fees::debit(tx, &account, fee)?;
|
|
||||||
let status = if unspent_micros == 0 {
|
let status = if unspent_micros == 0 {
|
||||||
"filled"
|
"filled"
|
||||||
} else {
|
} else {
|
||||||
@@ -357,7 +358,7 @@ pub(crate) fn settle(
|
|||||||
params![execution, taker.map(Taker::seq)],
|
params![execution, taker.map(Taker::seq)],
|
||||||
)?;
|
)?;
|
||||||
if let Some(taker) = taker {
|
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 {
|
if fee > 0 {
|
||||||
tx.execute(
|
tx.execute(
|
||||||
"INSERT INTO execution_fees VALUES(?,?,?)",
|
"INSERT INTO execution_fees VALUES(?,?,?)",
|
||||||
|
|||||||
@@ -254,6 +254,9 @@ pub(crate) enum Query {
|
|||||||
Positions(crate::portfolio::Filter),
|
Positions(crate::portfolio::Filter),
|
||||||
OpenInterest(crate::open_interest::Request),
|
OpenInterest(crate::open_interest::Request),
|
||||||
Holders(crate::holders::Request),
|
Holders(crate::holders::Request),
|
||||||
|
Balance {
|
||||||
|
account: String,
|
||||||
|
},
|
||||||
PortfolioValue {
|
PortfolioValue {
|
||||||
account: String,
|
account: String,
|
||||||
},
|
},
|
||||||
@@ -305,6 +308,7 @@ impl Query {
|
|||||||
Self::Resolution { market } => crate::resolution::read(db, &market),
|
Self::Resolution { market } => crate::resolution::read(db, &market),
|
||||||
Self::Assets { market } => assets::market_assets(db, &market),
|
Self::Assets { market } => assets::market_assets(db, &market),
|
||||||
Self::Activity(filter) => filter.read(db),
|
Self::Activity(filter) => filter.read(db),
|
||||||
|
Self::Balance { account } => crate::ledger::balance(db, &account),
|
||||||
Self::PortfolioValue { account } => crate::portfolio::value(db, &account),
|
Self::PortfolioValue { account } => crate::portfolio::value(db, &account),
|
||||||
Self::Holders(request) => request.read(db),
|
Self::Holders(request) => request.read(db),
|
||||||
Self::OpenInterest(request) => request.read(db),
|
Self::OpenInterest(request) => request.read(db),
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ use serde::Deserialize;
|
|||||||
pub(crate) enum Command {
|
pub(crate) enum Command {
|
||||||
Fund {
|
Fund {
|
||||||
account: String,
|
account: String,
|
||||||
cents: i64,
|
cents: Option<i64>,
|
||||||
|
micros: Option<i64>,
|
||||||
},
|
},
|
||||||
Event(crate::catalog::Event),
|
Event(crate::catalog::Event),
|
||||||
List {
|
List {
|
||||||
|
|||||||
+17
-27
@@ -1,4 +1,3 @@
|
|||||||
use crate::ledger;
|
|
||||||
use anyhow::{ensure, Result};
|
use anyhow::{ensure, Result};
|
||||||
use matching::Fill;
|
use matching::Fill;
|
||||||
use rusqlite::{params, Connection, Transaction};
|
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))?)
|
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
|
// Price and rate both have six decimals. Round the fee only after the
|
||||||
// ten micros, suppressing amounts below the published minimum.
|
// complete fill, to the nearest ten micros, with the published minimum.
|
||||||
pub(crate) fn micros(rate: i64, price: i64, shares: i64) -> i64 {
|
pub(crate) fn micros(rate: i64, price_micros: i64, shares: i64) -> i64 {
|
||||||
let numerator =
|
let numerator = i128::from(shares)
|
||||||
i128::from(shares) * i128::from(rate) * i128::from(price) * i128::from(100 - price);
|
* i128::from(rate)
|
||||||
if numerator < 100_000 {
|
* i128::from(price_micros)
|
||||||
|
* i128::from(1_000_000 - price_micros);
|
||||||
|
let denominator = 10_000_000_000_000;
|
||||||
|
if numerator < denominator {
|
||||||
return 0;
|
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 {
|
pub(crate) fn total(rate: i64, fills: &[Fill]) -> i64 {
|
||||||
fills
|
fills
|
||||||
.iter()
|
.iter()
|
||||||
.map(|f| micros(rate, f.price, f.quantity))
|
.map(|f| micros(rate, f.price * 10000, f.quantity))
|
||||||
.sum()
|
.sum()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,7 +37,8 @@ pub(crate) fn fit_budget(rate: i64, fills: &mut Vec<Fill>, budget: i64) {
|
|||||||
let mut count = 0;
|
let mut count = 0;
|
||||||
for f in fills.iter_mut() {
|
for f in fills.iter_mut() {
|
||||||
let cost = |qty: i64| {
|
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) {
|
if cost(f.quantity) <= i128::from(remaining) {
|
||||||
remaining -= cost(f.quantity) as i64;
|
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);
|
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<()> {
|
pub(crate) fn configure(tx: &Transaction, market: &str, rate: i64) -> Result<()> {
|
||||||
ensure!((0..=1_000_000).contains(&rate), "invalid taker fee rate");
|
ensure!((0..=1_000_000).contains(&rate), "invalid taker fee rate");
|
||||||
tx.execute(
|
tx.execute(
|
||||||
@@ -90,6 +78,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn symmetric_taker_curve_matches_published_examples_and_minimum() {
|
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 [
|
for (rate, price, size, expected) in [
|
||||||
(50000, 50, 100, 1250000),
|
(50000, 50, 100, 1250000),
|
||||||
(50000, 30, 100, 1050000),
|
(50000, 30, 100, 1050000),
|
||||||
@@ -101,8 +91,8 @@ mod tests {
|
|||||||
(1, 50, 60, 20),
|
(1, 50, 60, 20),
|
||||||
(50000, 0, 1, 0),
|
(50000, 0, 1, 0),
|
||||||
] {
|
] {
|
||||||
assert_eq!(micros(rate, price, size), expected);
|
assert_eq!(micros(rate, price * 10000, size), expected);
|
||||||
assert_eq!(micros(rate, 100 - price, size), expected);
|
assert_eq!(micros(rate, (100 - price) * 10000, size), expected);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
use anyhow::{ensure, Result};
|
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<()> {
|
pub(crate) fn cash(tx: &Transaction, account: &str, delta: i64) -> Result<()> {
|
||||||
ensure!(
|
ensure!(
|
||||||
@@ -12,6 +13,41 @@ pub(crate) fn cash(tx: &Transaction, account: &str, delta: i64) -> Result<()> {
|
|||||||
Ok(())
|
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(
|
pub(crate) fn position(
|
||||||
tx: &Transaction,
|
tx: &Transaction,
|
||||||
account: &str,
|
account: &str,
|
||||||
|
|||||||
@@ -111,6 +111,7 @@ impl Exchange {
|
|||||||
| "open_orders"
|
| "open_orders"
|
||||||
| "positions"
|
| "positions"
|
||||||
| "holders"
|
| "holders"
|
||||||
|
| "balance"
|
||||||
| "portfolio_value"
|
| "portfolio_value"
|
||||||
| "open_interest"
|
| "open_interest"
|
||||||
| "trades"
|
| "trades"
|
||||||
|
|||||||
@@ -16,11 +16,32 @@ pub(crate) fn apply(
|
|||||||
request_id: &str,
|
request_id: &str,
|
||||||
) -> Result<Value> {
|
) -> Result<Value> {
|
||||||
match command {
|
match command {
|
||||||
Command::Fund { account, cents } => {
|
Command::Fund {
|
||||||
|
account,
|
||||||
|
cents,
|
||||||
|
micros,
|
||||||
|
} => {
|
||||||
identifier(&account)?;
|
identifier(&account)?;
|
||||||
amount(cents)?;
|
let value = match (cents, micros) {
|
||||||
tx.execute("INSERT INTO accounts VALUES(?,?)", params![account, cents])?;
|
(Some(c), None) => {
|
||||||
Ok(json!({"funded":cents}))
|
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::Event(event) => event.save(tx),
|
||||||
Command::List {
|
Command::List {
|
||||||
|
|||||||
@@ -70,7 +70,8 @@ impl MinimumSize {
|
|||||||
// Whole shares are the simulator's executable quantity unit. The
|
// Whole shares are the simulator's executable quantity unit. The
|
||||||
// submitted cash cap includes the taker fee at the protection price.
|
// submitted cash cap includes the taker fee at the protection price.
|
||||||
let qty = (self.0 + SCALE - 1) / SCALE;
|
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!(
|
ensure!(
|
||||||
cents * 10000 >= required,
|
cents * 10000 >= required,
|
||||||
"cash budget at protection price is below min_order_size of {} shares",
|
"cash budget at protection price is below min_order_size of {} shares",
|
||||||
|
|||||||
@@ -2117,3 +2117,70 @@ fn single_and_batch_execution_prices_follow_opposing_liquidity() {
|
|||||||
assert!(reader.execute(invalid).is_err());
|
assert!(reader.execute(invalid).is_err());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn collateral_query_reconciles_subcent_funding_reservations_and_trade() {
|
||||||
|
let dir = tempdir().unwrap();
|
||||||
|
let path = dir.path().join("subcent.db");
|
||||||
|
let mut exchange = Exchange::open(&path).unwrap();
|
||||||
|
let balance = json!({"op":"balance","account":"buyer"});
|
||||||
|
for line in include_str!("../../../docs/examples/cash-balance.jsonl").lines() {
|
||||||
|
let cmd: Value = serde_json::from_str(line).unwrap();
|
||||||
|
if cmd["id"] == "trade" {
|
||||||
|
exchange
|
||||||
|
.execute(json!({"op":"fund","id":"short","account":"short","micros":512499}))
|
||||||
|
.unwrap();
|
||||||
|
let mut short = cmd.clone();
|
||||||
|
short["id"] = json!("failed");
|
||||||
|
short["account"] = json!("short");
|
||||||
|
let before = state(&mut exchange);
|
||||||
|
assert!(exchange.execute(short).is_err());
|
||||||
|
assert_eq!(state(&mut exchange), before);
|
||||||
|
}
|
||||||
|
let response = exchange.execute(cmd.clone()).unwrap();
|
||||||
|
match cmd["id"].as_str() {
|
||||||
|
Some("seller") => assert_eq!(response, json!({"funded":100})),
|
||||||
|
Some("buyer") => assert_eq!(response, json!({"funded":51,"funded_micros":512500})),
|
||||||
|
Some("rest") => assert_eq!(
|
||||||
|
exchange.execute(balance.clone()).unwrap(),
|
||||||
|
json!({"account":"buyer","available_micros":22500,"reserved_micros":490000,"total_cash_micros":512500})
|
||||||
|
),
|
||||||
|
Some("withdraw") => assert_eq!(
|
||||||
|
exchange.execute(balance.clone()).unwrap()["available_micros"],
|
||||||
|
512500
|
||||||
|
),
|
||||||
|
Some("trade") => assert_eq!(response["fee_micros"], 12500),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
if cmd["op"] == "activity" {
|
||||||
|
assert_eq!(response["activity"][0]["net_cash_delta_micros"], -512500);
|
||||||
|
assert_eq!(response["activity"][1]["net_cash_delta_micros"], 512500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
drop(exchange);
|
||||||
|
let mut exchange = Exchange::open(&path).unwrap();
|
||||||
|
assert_eq!(exchange.execute(balance).unwrap()["total_cash_micros"], 0);
|
||||||
|
assert_eq!(
|
||||||
|
exchange
|
||||||
|
.execute(json!({"op":"balance","account":"seller"}))
|
||||||
|
.unwrap()["total_cash_micros"],
|
||||||
|
500000
|
||||||
|
);
|
||||||
|
let repeat = json!({"op":"fund","id":"buyer","account":"buyer","micros":512500});
|
||||||
|
assert_eq!(exchange.execute(repeat).unwrap()["funded_micros"], 512500);
|
||||||
|
for invalid in [
|
||||||
|
json!({"micros":0}),
|
||||||
|
json!({"cents":1,"micros":1}),
|
||||||
|
json!({"micros":10000000000001_i64}),
|
||||||
|
json!({}),
|
||||||
|
] {
|
||||||
|
let mut request = invalid;
|
||||||
|
request["op"] = json!("fund");
|
||||||
|
request["account"] = json!("invalid");
|
||||||
|
request["id"] = json!("invalid");
|
||||||
|
assert!(exchange.execute(request).is_err());
|
||||||
|
}
|
||||||
|
assert!(exchange
|
||||||
|
.execute(json!({"op":"balance","account":"invalid"}))
|
||||||
|
.is_err());
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{"op":"fund","id":"seller","account":"seller","cents":100}
|
||||||
|
{"op":"fund","id":"buyer","account":"buyer","micros":512500}
|
||||||
|
{"op":"list","id":"market","market":"m","rules":"Official result","taker_fee_rate_ppm":50000}
|
||||||
|
{"op":"split","id":"split","market":"m","account":"seller","qty":1}
|
||||||
|
{"op":"open","id":"open","market":"m"}
|
||||||
|
{"op":"order","id":"rest","market":"m","outcome":"YES","account":"buyer","side":"buy","price":49,"qty":1}
|
||||||
|
{"op":"balance","account":"buyer"}
|
||||||
|
{"op":"cancel_all","id":"withdraw","account":"buyer"}
|
||||||
|
{"op":"order","id":"offer","market":"m","outcome":"YES","account":"seller","side":"sell","price":50,"qty":1}
|
||||||
|
{"op":"order","id":"trade","market":"m","outcome":"YES","account":"buyer","side":"buy","price":50,"qty":1,"tif":"FOK"}
|
||||||
|
{"op":"balance","account":"buyer"}
|
||||||
|
{"op":"activity","account":"buyer","include_deposits":true}
|
||||||
@@ -222,3 +222,11 @@ list 接受十进制份额字符串,最多六位小数;book、assets 和事
|
|||||||
`price` 接受 token_id 和方向,BUY 读取最低卖价,SELL 读取最高买价。单笔响应的 price 为十进制字符串。`prices` 在 requests 中接受最多 500 对资产与方向,在同一读快照中返回按资产和方向索引的 JSON 数值,匹配官方 REST 文档的样例类型。客户端可以直接为多个结果填入买卖按钮。大单仍需通过 estimate 按深度估算成交金额。[官方单笔与批量报价](https://docs.polymarket.com/market-data/prices-order-books.md#best-market-price)
|
`price` 接受 token_id 和方向,BUY 读取最低卖价,SELL 读取最高买价。单笔响应的 price 为十进制字符串。`prices` 在 requests 中接受最多 500 对资产与方向,在同一读快照中返回按资产和方向索引的 JSON 数值,匹配官方 REST 文档的样例类型。客户端可以直接为多个结果填入买卖按钮。大单仍需通过 estimate 按深度估算成交金额。[官方单笔与批量报价](https://docs.polymarket.com/market-data/prices-order-books.md#best-market-price)
|
||||||
|
|
||||||
[可重放样例](examples/execution-prices.jsonl)开始时只有 YES 买单,买入 YES 的报价为 null。随后有人以 0.89 挂买 NO,YES 买入价变成 0.11,卖出价为 0.09。NO 买入价为 0.91,卖出价为 0.89。这四个报价均来自挂单,无需先发生交易。单侧没有对手时保留该键并返回 null。重复项合并,未知资产使整批失败。空批次拒绝,盘前返回待集合竞价的挂单报价。上述边界属于本地约定。本地 token_id 使用 Eventbook 的结果资产 ID,公开接口的生产响应、原生资产编号与无流动性时的处理仍待对照。
|
[可重放样例](examples/execution-prices.jsonl)开始时只有 YES 买单,买入 YES 的报价为 null。随后有人以 0.89 挂买 NO,YES 买入价变成 0.11,卖出价为 0.09。NO 买入价为 0.91,卖出价为 0.89。这四个报价均来自挂单,无需先发生交易。单侧没有对手时保留该键并返回 null。重复项合并,未知资产使整批失败。空批次拒绝,盘前返回待集合竞价的挂单报价。上述边界属于本地约定。本地 token_id 使用 Eventbook 的结果资产 ID,公开接口的生产响应、原生资产编号与无流动性时的处理仍待对照。
|
||||||
|
|
||||||
|
## 精确抵押币现金余额
|
||||||
|
|
||||||
|
`balance` 返回账户可用现金、有效买单预留现金及二者之和,单位均为百万分之一模拟美元。拆分完整结果集所用的抵押和已买入的份额另由仓位账本记录。模拟 fund 可以用整数 micros 建立账户,也可以沿用 cents。入金回执和 activity 的 net_cash_delta_micros 可用于精确对账,原 funded 和 cash_delta_cents 字段保留整分部分。一个账户只接受首次 fund;相同请求可幂等重放。
|
||||||
|
|
||||||
|
[现金与费用样例](examples/cash-balance.jsonl)中,买家以 512500 微单位开户,先挂 49 分买单,仍有 22500 微单位可用。撤单后以 50 分买入一份,费率 0.05,对应费用 12500 微单位,买方余额恰为零。若初始现金少一个微单位,交易整体回滚。
|
||||||
|
|
||||||
|
费用函数使用六位小数的价格计算本金两侧的价格因子。例如 5 份、单价 0.013、费率 0.05,按目前的逐笔五位小数舍入约定收取 3210 微单位。正常下单入口的价格和预算仍以分输入;该价格算例覆盖费用运算,细价格限价单的提交与交割仍待接入。官方 SDK 对限价单按市场步长和数量精度推导抵押金额。这里的 fund 和 balance 是本地模拟账本接口,外场的授权额度及链上钱包余额需要分别对照。[官方 SDK 的订单金额计算](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/order_builder/builder.py) · [官方费用公式](https://docs.polymarket.com/trading/fees.md)
|
||||||
|
|||||||
Reference in New Issue
Block a user