Match fractional share lots and preserve order quantities across restart
This commit is contained in:
@@ -572,7 +572,7 @@ sequenceDiagram
|
||||
C->>E: estimate 或下单
|
||||
E->>D: 读取市场费率
|
||||
E->>B: 按价格和时间取候选成交
|
||||
E->>E: 逐笔计算吃单费,预算买单截取含费可买的整份
|
||||
E->>E: 逐笔计算吃单费,预算买单截取含费可买的数量,精确到 0.01 份
|
||||
alt 预估
|
||||
E-->>C: 预期费用、净现金与可执行性
|
||||
else 下单
|
||||
@@ -674,7 +674,7 @@ sequenceDiagram
|
||||
E->>D: 按市场查步长和最小份额
|
||||
E->>E: 校验价格、向下取百分之一份、计算抵押金额
|
||||
E-->>C: 返回 makerAmount、takerAmount 和本地精度支持标记
|
||||
C->>E: order 提交整分价格与整份数量
|
||||
C->>E: order 提交整分价格,份额按 0.01 份向下取整
|
||||
E->>D: 检查价格符合市场步长
|
||||
E->>B: 盘前挂单或连续撮合
|
||||
O->>E: open
|
||||
@@ -764,3 +764,35 @@ sequenceDiagram
|
||||
C->>E: 重启后重发相同兑付请求
|
||||
E-->>C: 返回已提交回执
|
||||
```
|
||||
|
||||
### 委托数量的持久化与恢复
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
lib["lib.rs"] --> lots["lots.rs"]
|
||||
lots --> migration["lot_migration.sql"]
|
||||
market["market.rs"] --> lots
|
||||
market --> book["book.rs"]
|
||||
book --> resident["resident.rs"]
|
||||
book --> ledger["ledger.rs / inventory.rs"]
|
||||
book --> fees["fees.rs"]
|
||||
resident --> matching["matching::OrderBook"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant E as Exchange
|
||||
participant B as 内存订单簿
|
||||
participant D as SQLite
|
||||
C->>E: 限价卖出 1.239999 份
|
||||
E->>D: 预留 1.23 份,写入 123 个数量单位
|
||||
E->>B: 提交后按原受理号安装订单
|
||||
C->>E: 以限价买入 0.50 份
|
||||
E->>B: 盘中立即扫单,盘前则在开盘时统一竞价
|
||||
B-->>E: 分配 50 个单位,保留原卖单优先级
|
||||
E->>D: 记录成交并将余量更新为 73,提交后同步内存
|
||||
E->>D: 重启按原单号装载 73 个单位
|
||||
C->>E: 撤销余单
|
||||
E->>D: 退回 0.73 份
|
||||
```
|
||||
|
||||
@@ -44,7 +44,7 @@ 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,
|
||||
b.amount_cents,COALESCE((SELECT micros FROM budget_spend_micros WHERE order_seq=orders.seq),b.spent_cents*10000),
|
||||
(SELECT COALESCE(SUM(fee_micros),0) FROM execution_fees WHERE taker_order=orders.seq),
|
||||
(SELECT key_id FROM order_keys WHERE order_seq=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)
|
||||
@@ -76,10 +76,10 @@ impl Filter {
|
||||
orders.push(
|
||||
json!({"order":id,"market":market,"asset_id":crate::assets::id(&market,&outcome),
|
||||
"outcome":outcome,"side":row.get::<_,String>(3)?,
|
||||
"price_micros":row.get::<_,i64>(4)?*10000,"original_size":quantity,
|
||||
"size_matched":quantity-remaining,"open_size":if status=="live"{remaining}else{0},
|
||||
"price_micros":row.get::<_,i64>(4)?*10000,"original_size":crate::lots::display(quantity),
|
||||
"size_matched":crate::lots::display(quantity-remaining),"open_size":crate::lots::display(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)?,"fee_micros":row.get::<_,i64>(11)?,"key_id":row.get::<_,Option<String>>(12)?}),
|
||||
"amount_cents":row.get::<_,Option<i64>>(9)?,"spent_cents":row.get::<_,Option<i64>>(10)?.map(|v|crate::inventory::decimal(v.into(),10000)),"fee_micros":row.get::<_,i64>(11)?,"key_id":row.get::<_,Option<String>>(12)?}),
|
||||
);
|
||||
last_id = Some(id);
|
||||
}
|
||||
|
||||
@@ -63,8 +63,8 @@ impl Filter {
|
||||
trades.push(
|
||||
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,"fee_micros":r.get::<_,i64>(10)?,"at_ms":r.get::<_,Option<i64>>(8)?,
|
||||
"kind":r.get::<_,String>(5)?,"price_micros":price*10000,"size":crate::lots::display(size),
|
||||
"gross_cents":crate::inventory::decimal(i128::from(price)*i128::from(size),100),"fee_micros":r.get::<_,i64>(10)?,"at_ms":r.get::<_,Option<i64>>(8)?,
|
||||
"role":r.get::<_,Option<String>>(9)?}),
|
||||
);
|
||||
last = Some((execution, order));
|
||||
|
||||
@@ -8,10 +8,10 @@ WITH activity(source,seq,leg,at_ms,kind,market,group_id,shares,cash_delta,reques
|
||||
)
|
||||
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),
|
||||
CASE WHEN kind='DEPOSIT' THEN (SELECT json_extract(response,'$.funded_micros')
|
||||
CASE WHEN source=1 THEN cash_delta*100 WHEN kind='DEPOSIT' THEN (SELECT json_extract(response,'$.funded_micros')
|
||||
FROM requests WHERE id=activity.request_id) ELSE
|
||||
(SELECT cash_micros FROM precise_movements WHERE request_id=activity.request_id AND account=?1) END,
|
||||
(SELECT shares_micros FROM precise_movements WHERE request_id=activity.request_id AND account=?1)
|
||||
CASE WHEN source=1 THEN shares*10000 ELSE (SELECT shares_micros FROM precise_movements WHERE request_id=activity.request_id AND account=?1) END
|
||||
FROM activity
|
||||
WHERE (?2 IS NULL OR market=?2)
|
||||
AND (?3 IS NULL OR kind IN (SELECT value FROM json_each(?3)))
|
||||
|
||||
+41
-30
@@ -25,12 +25,12 @@ pub(crate) struct ShareExecution {
|
||||
pub seq: i64,
|
||||
pub filled: i64,
|
||||
pub status: String,
|
||||
pub gross_cents: i64,
|
||||
pub gross_micros: i64,
|
||||
pub fee_micros: i64,
|
||||
}
|
||||
impl ShareExecution {
|
||||
pub fn receipt(&self) -> Value {
|
||||
let mut receipt = json!({"order":self.seq,"filled":self.filled,"status":self.status});
|
||||
let mut receipt = json!({"order":self.seq,"filled":crate::lots::display(self.filled),"status":self.status});
|
||||
if self.fee_micros > 0 {
|
||||
receipt["fee_micros"] = json!(self.fee_micros);
|
||||
}
|
||||
@@ -38,8 +38,8 @@ impl ShareExecution {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn gross_cents(fills: &[Fill]) -> i64 {
|
||||
fills.iter().map(|f| f.price * f.quantity).sum()
|
||||
pub(crate) fn gross_micros(fills: &[Fill]) -> i64 {
|
||||
fills.iter().map(|f| f.price * f.quantity * 100).sum()
|
||||
}
|
||||
|
||||
pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result<ShareExecution> {
|
||||
@@ -56,7 +56,10 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
post_only,
|
||||
} = order;
|
||||
identifier(&account)?;
|
||||
amount(qty)?;
|
||||
ensure!(
|
||||
(1..=100_000_000_000).contains(&qty),
|
||||
"invalid order quantity"
|
||||
);
|
||||
let stage = phase(tx, &market, &["preopen", "continuous"])?;
|
||||
ensure!(
|
||||
matches!(outcome.as_str(), "YES" | "NO") && matches!(side.as_str(), "buy" | "sell"),
|
||||
@@ -72,7 +75,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
"post-only requires continuous GTC or GTD"
|
||||
);
|
||||
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
|
||||
minimum.check_shares(qty)?;
|
||||
minimum.check_microshares(qty * crate::lots::MICROS)?;
|
||||
}
|
||||
if let Some(tick) = crate::tick_size::TickSize::load(tx, &market)? {
|
||||
tick.check(price * 10000)?;
|
||||
@@ -94,9 +97,9 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
}
|
||||
};
|
||||
if side == "buy" {
|
||||
ledger::cash(tx, &account, -price * qty)?;
|
||||
ledger::cash_micros(tx, &account, -price * qty * 100)?;
|
||||
} else {
|
||||
ledger::position(tx, &account, &market, &outcome, -qty)?;
|
||||
crate::inventory::position(tx, &account, &market, &outcome, -qty * crate::lots::MICROS)?;
|
||||
}
|
||||
tx.execute("INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status) VALUES(?,?,?,?,?,?,?,'live')",params![account,market,outcome,side,price,qty,qty])?;
|
||||
let seq = tx.last_insert_rowid();
|
||||
@@ -134,7 +137,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
tif != TimeInForce::Fak || !fills.is_empty(),
|
||||
"FAK has no matching liquidity"
|
||||
);
|
||||
gross = gross_cents(&fills);
|
||||
gross = gross_micros(&fills);
|
||||
fee_micros = settle(tx, &market, &outcome, fills, Some(Taker::Limit(seq)))?;
|
||||
}
|
||||
let (remaining, mut status): (i64, String) = tx.query_row(
|
||||
@@ -154,7 +157,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
seq,
|
||||
filled: qty - remaining,
|
||||
status,
|
||||
gross_cents: gross,
|
||||
gross_micros: gross,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -206,14 +209,14 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
|
||||
crate::heartbeat::record_key(tx, seq, key_id.as_deref())?;
|
||||
let mut fills = books
|
||||
.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 * 100))
|
||||
.unwrap_or_default();
|
||||
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 gross_remainder = amount_cents - spent;
|
||||
let unspent_micros = gross_remainder * 10000 - crate::fees::total(rate, &fills);
|
||||
let spent = gross_micros(&fills);
|
||||
let gross_remainder = amount_cents * 10000 - spent;
|
||||
let unspent_micros = gross_remainder - crate::fees::total(rate, &fills);
|
||||
ensure!(
|
||||
tif != TimeInForce::Fok || unspent_micros == 0,
|
||||
"FOK cannot fill the entire cash amount"
|
||||
@@ -224,21 +227,25 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO budget_buys(order_seq,amount_cents,spent_cents) VALUES(?,?,?)",
|
||||
params![seq, amount_cents, spent],
|
||||
params![seq, amount_cents, spent / 10000],
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO budget_spend_micros VALUES(?,?)",
|
||||
params![seq, spent],
|
||||
)?;
|
||||
let fee = settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?;
|
||||
ledger::cash_micros(tx, &account, gross_remainder * 10000 - fee)?;
|
||||
ledger::cash_micros(tx, &account, gross_remainder - fee)?;
|
||||
let status = if unspent_micros == 0 {
|
||||
"filled"
|
||||
} else {
|
||||
tx.execute("UPDATE orders SET status='cancelled' WHERE seq=?", [seq])?;
|
||||
"cancelled"
|
||||
};
|
||||
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 {
|
||||
let mut receipt = json!({"order":seq,"status":status,"filled":crate::lots::display(quantity),"amount_cents":amount_cents,"spent_cents":crate::inventory::decimal(spent.into(),10000),"unspent_cents":crate::inventory::decimal(unspent_micros.into(),10000)});
|
||||
if fee > 0 || spent % 10000 != 0 {
|
||||
receipt["fee_micros"] = json!(fee);
|
||||
receipt["unspent_micros"] = json!(unspent_micros);
|
||||
receipt["total_spent_micros"] = json!(spent * 10000 + fee);
|
||||
receipt["total_spent_micros"] = json!(spent + fee);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
@@ -285,12 +292,20 @@ fn book_leg(
|
||||
if side == "buy" {
|
||||
ensure!(price <= limit, "buy limit exceeded");
|
||||
if taker != Some(Taker::Budget(seq)) {
|
||||
ledger::cash(tx, &account, (limit - price) * fill.quantity)?;
|
||||
ledger::cash_micros(tx, &account, (limit - price) * fill.quantity * 100)?;
|
||||
}
|
||||
ledger::position(tx, &account, market, &outcome, fill.quantity)?;
|
||||
crate::inventory::position(
|
||||
tx,
|
||||
&account,
|
||||
market,
|
||||
&outcome,
|
||||
fill.quantity
|
||||
.checked_mul(crate::lots::MICROS)
|
||||
.ok_or_else(|| anyhow::anyhow!("fill exceeds ledger range"))?,
|
||||
)?;
|
||||
} else {
|
||||
ensure!(price >= limit, "sell limit exceeded");
|
||||
ledger::cash(tx, &account, price * fill.quantity)?;
|
||||
ledger::cash_micros(tx, &account, price * fill.quantity * 100)?;
|
||||
}
|
||||
Ok(ExecutedLeg {
|
||||
seq,
|
||||
@@ -328,11 +343,7 @@ pub(crate) fn settle(
|
||||
} else {
|
||||
ensure!(first.side == second.side, "invalid complementary legs");
|
||||
let mint = first.side == "buy";
|
||||
let delta = if mint {
|
||||
100 * f.quantity
|
||||
} else {
|
||||
-100 * f.quantity
|
||||
};
|
||||
let delta = if mint { f.quantity } else { -f.quantity };
|
||||
ensure!(
|
||||
tx.execute(
|
||||
"UPDATE markets SET collateral=collateral+?1 WHERE id=?2 AND collateral+?1>=0",
|
||||
@@ -364,7 +375,7 @@ pub(crate) fn settle(
|
||||
params![execution, taker.map(Taker::seq)],
|
||||
)?;
|
||||
if let Some(taker) = taker {
|
||||
let fee = crate::fees::micros(rate, f.price * 10000, f.quantity);
|
||||
let fee = crate::fees::lot_fee(rate, f.price * 10000, f.quantity);
|
||||
if fee > 0 {
|
||||
tx.execute(
|
||||
"INSERT INTO execution_fees VALUES(?,?,?)",
|
||||
@@ -393,9 +404,9 @@ pub(crate) fn release(
|
||||
) -> Result<i64> {
|
||||
let (market,outcome,side,price,qty):(String,String,String,i64,i64)=tx.query_row("SELECT market,outcome,side,price,remaining FROM orders WHERE seq=? AND account=? AND status='live'",params![seq,owner],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
|
||||
if side == "buy" {
|
||||
ledger::cash(tx, owner, price * qty)?;
|
||||
ledger::cash_micros(tx, owner, price * qty * 100)?;
|
||||
} else {
|
||||
ledger::position(tx, owner, &market, &outcome, qty)?;
|
||||
crate::inventory::position(tx, owner, &market, &outcome, qty * crate::lots::MICROS)?;
|
||||
}
|
||||
let status = match reason {
|
||||
CancelReason::Cancelled => "cancelled",
|
||||
|
||||
@@ -334,7 +334,9 @@ impl Query {
|
||||
let price: i64 = row.get(1)?;
|
||||
let size: i64 = row.get(2)?;
|
||||
let levels = if side == "buy" { &mut bids } else { &mut asks };
|
||||
levels.push(json!({"price_micros":price*10000,"size":size}));
|
||||
levels.push(
|
||||
json!({"price_micros":price*10000,"size":crate::lots::display(size)}),
|
||||
);
|
||||
}
|
||||
let minimum =
|
||||
crate::minimum_size::MinimumSize::load(db, &market)?.map(|size| size.text());
|
||||
@@ -477,7 +479,7 @@ impl Query {
|
||||
Ok(json!({"at_ms":r.get::<_,i64>(0)?,
|
||||
"fill":r.get::<_,i64>(1)?,
|
||||
"price_micros":r.get::<_,i64>(2)?,
|
||||
"quantity":r.get::<_,i64>(3)?}))
|
||||
"quantity":crate::lots::display(r.get::<_,i64>(3)?)}))
|
||||
},
|
||||
)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
|
||||
@@ -71,7 +71,8 @@ pub(crate) enum Command {
|
||||
outcome: String,
|
||||
side: String,
|
||||
price: i64,
|
||||
qty: i64,
|
||||
qty: Option<i64>,
|
||||
size_micros: Option<i64>,
|
||||
#[serde(default)]
|
||||
tif: Option<TimeInForce>,
|
||||
expiration: Option<i64>,
|
||||
@@ -84,7 +85,8 @@ pub(crate) enum Command {
|
||||
account: String,
|
||||
key_id: Option<String>,
|
||||
outcome: String,
|
||||
qty: i64,
|
||||
qty: Option<i64>,
|
||||
size_micros: Option<i64>,
|
||||
min_price: i64,
|
||||
tif: Option<TimeInForce>,
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
assets,
|
||||
book::gross_cents,
|
||||
book::gross_micros,
|
||||
command::TimeInForce,
|
||||
resident::Books,
|
||||
validation::{amount, phase},
|
||||
@@ -24,7 +24,8 @@ pub(crate) enum Request {
|
||||
Sell {
|
||||
market: String,
|
||||
outcome: String,
|
||||
qty: i64,
|
||||
qty: Option<i64>,
|
||||
size_micros: Option<i64>,
|
||||
min_price: Option<i64>,
|
||||
tif: Option<TimeInForce>,
|
||||
},
|
||||
@@ -44,15 +45,25 @@ impl Request {
|
||||
market,
|
||||
outcome,
|
||||
qty,
|
||||
size_micros,
|
||||
min_price,
|
||||
tif,
|
||||
} => (market, outcome, Side::Sell, qty, min_price, tif),
|
||||
} => (
|
||||
market,
|
||||
outcome,
|
||||
Side::Sell,
|
||||
crate::lots::amount(qty, size_micros)?,
|
||||
min_price,
|
||||
tif,
|
||||
),
|
||||
};
|
||||
let tick = crate::tick_size::TickSize::load(tx, &market)?;
|
||||
let edge = tick.as_ref().map_or(0, |t| i64::from(t.local_step().get()));
|
||||
let limit = limit.unwrap_or(if side == Side::Buy { 100 - edge } else { edge });
|
||||
let tif = tif.unwrap_or(TimeInForce::Fak);
|
||||
amount(requested)?;
|
||||
if side == Side::Buy {
|
||||
amount(requested)?;
|
||||
}
|
||||
ensure!(
|
||||
matches!(tif, TimeInForce::Fak | TimeInForce::Fok),
|
||||
"estimate requires FAK or FOK"
|
||||
@@ -69,7 +80,7 @@ impl Request {
|
||||
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
|
||||
match side {
|
||||
Side::Buy => minimum.check_budget(requested, limit, rate)?,
|
||||
Side::Sell => minimum.check_shares(requested)?,
|
||||
Side::Sell => minimum.check_microshares(requested * crate::lots::MICROS)?,
|
||||
}
|
||||
}
|
||||
let changes = books.changes(tx)?;
|
||||
@@ -78,7 +89,7 @@ impl Request {
|
||||
let mut fills = books
|
||||
.get(&market, &outcome)
|
||||
.map(|b| match side {
|
||||
Side::Buy => b.match_budget_buy(i64::MAX, limit, requested),
|
||||
Side::Buy => b.match_budget_buy(i64::MAX, limit, requested * 100),
|
||||
Side::Sell => b.match_incoming(&Order {
|
||||
seq: i64::MAX,
|
||||
side,
|
||||
@@ -92,9 +103,9 @@ impl Request {
|
||||
}
|
||||
let fee = crate::fees::total(rate, &fills);
|
||||
let shares: i64 = fills.iter().map(|f| f.quantity).sum();
|
||||
let gross = gross_cents(&fills);
|
||||
let gross = gross_micros(&fills);
|
||||
let remaining_cash = if side == Side::Buy {
|
||||
(requested - gross) * 10000 - fee
|
||||
requested * 10000 - gross - fee
|
||||
} else {
|
||||
0
|
||||
};
|
||||
@@ -102,21 +113,22 @@ impl Request {
|
||||
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),
|
||||
let mut result = json!({"asset_id":assets::id(&market,&outcome),"filled_shares":crate::lots::display(shares),
|
||||
"gross_cents":crate::inventory::decimal(gross.into(),10000),"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),
|
||||
"average_price_micros":(i128::from(gross)*100).checked_div(i128::from(shares)),
|
||||
"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["total_spent_micros"] = json!(gross + fee);
|
||||
result["unspent_cents"] =
|
||||
json!(crate::inventory::decimal(remaining_cash.into(), 10000));
|
||||
result["unspent_micros"] = json!(remaining_cash);
|
||||
}
|
||||
Side::Sell => {
|
||||
result["net_proceeds_micros"] = json!(gross * 10000 - fee);
|
||||
result["unsold_shares"] = json!(requested - shares);
|
||||
result["net_proceeds_micros"] = json!(gross - fee);
|
||||
result["unsold_shares"] = json!(crate::lots::display(requested - shares));
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
|
||||
@@ -8,12 +8,17 @@ pub(crate) fn rate(db: &Connection, market: &str) -> Result<i64> {
|
||||
|
||||
// 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)
|
||||
#[cfg(test)]
|
||||
fn micros(rate: i64, price_micros: i64, shares: i64) -> i64 {
|
||||
lot_fee(rate, price_micros, shares * 100)
|
||||
}
|
||||
|
||||
pub(crate) fn lot_fee(rate: i64, price_micros: i64, lots: i64) -> i64 {
|
||||
let numerator = i128::from(lots)
|
||||
* i128::from(rate)
|
||||
* i128::from(price_micros)
|
||||
* i128::from(1_000_000 - price_micros);
|
||||
let denominator = 10_000_000_000_000;
|
||||
let denominator = 1_000_000_000_000_000;
|
||||
if numerator < denominator {
|
||||
return 0;
|
||||
}
|
||||
@@ -23,7 +28,7 @@ pub(crate) fn micros(rate: i64, price_micros: i64, shares: i64) -> i64 {
|
||||
pub(crate) fn total(rate: i64, fills: &[Fill]) -> i64 {
|
||||
fills
|
||||
.iter()
|
||||
.map(|f| micros(rate, f.price * 10000, f.quantity))
|
||||
.map(|f| lot_fee(rate, f.price * 10000, f.quantity))
|
||||
.sum()
|
||||
}
|
||||
|
||||
@@ -37,8 +42,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 * 10000, qty))
|
||||
i128::from(qty) * i128::from(f.price) * 100
|
||||
+ i128::from(lot_fee(rate, f.price * 10000, qty))
|
||||
};
|
||||
if cost(f.quantity) <= i128::from(remaining) {
|
||||
remaining -= cost(f.quantity) as i64;
|
||||
|
||||
@@ -43,7 +43,7 @@ pub(crate) fn backing(tx: &Transaction, market: &str, delta: i64) -> Result<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn position(
|
||||
pub(crate) fn position(
|
||||
tx: &Transaction,
|
||||
account: &str,
|
||||
market: &str,
|
||||
|
||||
@@ -41,7 +41,7 @@ pub(crate) fn balance(db: &Connection, account: &str) -> Result<Value> {
|
||||
|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;
|
||||
let reserved = i128::from(reserved) * 100;
|
||||
Ok(
|
||||
json!({"account":account, "available_micros":available, "reserved_micros":reserved,
|
||||
"total_cash_micros":available+reserved}),
|
||||
|
||||
@@ -19,6 +19,7 @@ mod command;
|
||||
mod inventory;
|
||||
mod kickoff;
|
||||
mod ledger;
|
||||
mod lots;
|
||||
mod market;
|
||||
mod minimum_size;
|
||||
mod neg_risk;
|
||||
@@ -44,7 +45,7 @@ pub struct Exchange {
|
||||
}
|
||||
impl Exchange {
|
||||
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
|
||||
let db = Connection::open(path)?;
|
||||
let mut db = Connection::open(path)?;
|
||||
db.busy_timeout(Duration::from_secs(10))?;
|
||||
db.execute_batch("PRAGMA foreign_keys=ON")?;
|
||||
db.execute_batch(include_str!("schema.sql"))?;
|
||||
@@ -77,6 +78,7 @@ impl Exchange {
|
||||
if !marks_ready {
|
||||
db.execute_batch(include_str!("valuation_schema.sql"))?;
|
||||
}
|
||||
lots::migrate(&mut db)?;
|
||||
let tx = expiry::transaction(&db, TransactionBehavior::Deferred)?;
|
||||
let books = Books::recover(&tx)?;
|
||||
tx.commit()?;
|
||||
@@ -169,6 +171,12 @@ impl Exchange {
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
let v = match row.get_ref(i)? {
|
||||
ValueRef::Null => Value::Null,
|
||||
ValueRef::Integer(n)
|
||||
if matches!(table, "orders" | "fills" | "paired_fills")
|
||||
&& matches!(name.as_str(), "quantity" | "remaining") =>
|
||||
{
|
||||
json!(lots::display(n))
|
||||
}
|
||||
ValueRef::Integer(n) => json!(n),
|
||||
ValueRef::Text(s) => json!(std::str::from_utf8(s)?),
|
||||
_ => anyhow::bail!("unexpected column type"),
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
-- Caller holds an IMMEDIATE transaction and checks the format marker under the lock.
|
||||
-- Fail the transaction if any integer would be promoted to SQLite REAL.
|
||||
CREATE TABLE order_lot_format (version INTEGER PRIMARY KEY CHECK(version=1));
|
||||
INSERT INTO order_lot_format
|
||||
SELECT CASE WHEN EXISTS(SELECT 1 FROM orders WHERE MAX(quantity,remaining)>92233720368547758)
|
||||
OR EXISTS(SELECT 1 FROM fills WHERE quantity>92233720368547758)
|
||||
OR EXISTS(SELECT 1 FROM paired_fills WHERE quantity>92233720368547758)
|
||||
OR EXISTS(SELECT 1 FROM trade_prices WHERE quantity>92233720368547758)
|
||||
THEN 0 ELSE 1 END;
|
||||
UPDATE orders SET quantity=quantity*100,remaining=remaining*100;
|
||||
UPDATE fills SET quantity=quantity*100;
|
||||
UPDATE paired_fills SET quantity=quantity*100;
|
||||
UPDATE trade_prices SET quantity=quantity*100;
|
||||
DROP VIEW position_units;
|
||||
CREATE VIEW position_units AS
|
||||
SELECT p.account,p.market,p.outcome,p.available*1000000+COALESCE(r.micros,0) AS available,
|
||||
p.reserved*10000 AS reserved,p.phase,p.payout_per_share
|
||||
FROM position_sizes p LEFT JOIN position_remainders r USING(account,market,outcome);
|
||||
@@ -0,0 +1,36 @@
|
||||
use anyhow::Result;
|
||||
use rusqlite::{Connection, TransactionBehavior};
|
||||
use serde_json::Number;
|
||||
|
||||
pub(crate) const PER_SHARE: i64 = 100;
|
||||
pub(crate) const MICROS: i64 = 10_000;
|
||||
pub(crate) fn display(lots: i64) -> Number {
|
||||
crate::inventory::decimal(lots.into(), PER_SHARE)
|
||||
}
|
||||
pub(crate) fn amount(qty: Option<i64>, size_micros: Option<i64>) -> Result<i64> {
|
||||
match (qty, size_micros) {
|
||||
(Some(whole), None) => {
|
||||
crate::validation::amount(whole)?;
|
||||
Ok(whole * PER_SHARE)
|
||||
}
|
||||
(None, Some(units)) if (MICROS..=1_000_000_000_000_000).contains(&units) => {
|
||||
Ok(units / MICROS)
|
||||
}
|
||||
_ => anyhow::bail!("provide one positive qty or size_micros within the quantity limit"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn migrate(db: &mut Connection) -> Result<()> {
|
||||
let ready = |c: &Connection| {
|
||||
c.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='order_lot_format')",[],|r|r.get::<_,bool>(0))
|
||||
};
|
||||
if ready(db)? {
|
||||
return Ok(());
|
||||
}
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
if !ready(&tx)? {
|
||||
tx.execute_batch(include_str!("lot_migration.sql"))?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -131,6 +131,7 @@ pub(crate) fn apply(
|
||||
side,
|
||||
price,
|
||||
qty,
|
||||
size_micros,
|
||||
tif,
|
||||
expiration,
|
||||
post_only,
|
||||
@@ -144,7 +145,7 @@ pub(crate) fn apply(
|
||||
outcome,
|
||||
side,
|
||||
price,
|
||||
qty,
|
||||
qty: crate::lots::amount(qty, size_micros)?,
|
||||
tif: tif.unwrap_or_else(|| {
|
||||
if expiration.unwrap_or(0) != 0 {
|
||||
crate::command::TimeInForce::Gtd
|
||||
@@ -164,6 +165,7 @@ pub(crate) fn apply(
|
||||
outcome,
|
||||
qty,
|
||||
min_price,
|
||||
size_micros,
|
||||
tif,
|
||||
} => {
|
||||
let tif = tif.unwrap_or(crate::command::TimeInForce::Fak);
|
||||
@@ -174,6 +176,7 @@ pub(crate) fn apply(
|
||||
),
|
||||
"market sell requires FAK or FOK"
|
||||
);
|
||||
let qty = crate::lots::amount(qty, size_micros)?;
|
||||
let result = book::submit(
|
||||
tx,
|
||||
books,
|
||||
@@ -191,11 +194,11 @@ pub(crate) fn apply(
|
||||
},
|
||||
)?;
|
||||
let mut receipt = result.receipt();
|
||||
receipt["proceeds_cents"] = json!(result.gross_cents);
|
||||
receipt["unsold_shares"] = json!(qty - result.filled);
|
||||
receipt["proceeds_cents"] =
|
||||
json!(crate::inventory::decimal(result.gross_micros.into(), 10000));
|
||||
receipt["unsold_shares"] = json!(crate::lots::display(qty - result.filled));
|
||||
if result.fee_micros > 0 {
|
||||
receipt["net_proceeds_micros"] =
|
||||
json!(result.gross_cents * 10000 - result.fee_micros);
|
||||
receipt["net_proceeds_micros"] = json!(result.gross_micros - result.fee_micros);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
@@ -223,7 +226,7 @@ pub(crate) fn apply(
|
||||
Command::Cancel { order, account } => {
|
||||
identifier(&account)?;
|
||||
let qty = book::release(tx, order, &account, book::CancelReason::Cancelled)?;
|
||||
Ok(json!({"cancelled":qty}))
|
||||
Ok(json!({"cancelled":crate::lots::display(qty)}))
|
||||
}
|
||||
Command::CancelOrders { account, orders } => {
|
||||
crate::cancellation::by_id(tx, &account, &orders)
|
||||
|
||||
@@ -57,10 +57,6 @@ impl MinimumSize {
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
pub fn check_shares(&self, qty: i64) -> Result<()> {
|
||||
self.check_microshares(qty * SCALE)
|
||||
}
|
||||
|
||||
pub fn check_microshares(&self, shares: i64) -> Result<()> {
|
||||
ensure!(
|
||||
shares >= self.0,
|
||||
@@ -71,11 +67,9 @@ impl MinimumSize {
|
||||
}
|
||||
|
||||
pub fn check_budget(&self, cents: i64, max_price: i64, fee_rate: i64) -> Result<()> {
|
||||
// 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 lots = (self.0 + crate::lots::MICROS - 1) / crate::lots::MICROS;
|
||||
let required =
|
||||
qty * max_price * 10000 + crate::fees::micros(fee_rate, max_price * 10000, qty);
|
||||
lots * max_price * 100 + crate::fees::lot_fee(fee_rate, max_price * 10000, lots);
|
||||
ensure!(
|
||||
cents * 10000 >= required,
|
||||
"cash budget at protection price is below min_order_size of {} shares",
|
||||
|
||||
@@ -126,7 +126,7 @@ impl Request {
|
||||
let size: i64 = r.get(9)?;
|
||||
data.push(json!({"at_ms":at,"execution":seq,"account":r.get::<_,String>(3)?,"market":market,
|
||||
"outcome":outcome,"asset_id":assets::id(&market,&outcome),"side":r.get::<_,String>(6)?,
|
||||
"kind":r.get::<_,String>(7)?,"price_micros":price*10000,"size":size,"gross_cents":price*size,
|
||||
"kind":r.get::<_,String>(7)?,"price_micros":price*10000,"size":crate::lots::display(size),"gross_cents":crate::inventory::decimal(i128::from(price)*i128::from(size),100),
|
||||
"role":r.get::<_,Option<String>>(10)?}));
|
||||
page.before = (at, seq, r.get(2)?);
|
||||
}
|
||||
|
||||
@@ -26,5 +26,5 @@ WITH selected_events AS (
|
||||
AND (e.at_ms,e.execution,o.seq)<(:before_ms,:before_execution,:before_order)
|
||||
)
|
||||
SELECT at_ms,execution,order_seq,account,market,outcome,side,kind,price,quantity,role
|
||||
FROM legs WHERE CASE WHEN :cash THEN price*quantity/100.0 ELSE quantity END >= :minimum
|
||||
FROM legs WHERE CASE WHEN :cash THEN price*quantity/10000.0 ELSE quantity/100.0 END >= :minimum
|
||||
ORDER BY at_ms DESC,execution DESC,order_seq DESC LIMIT :limit
|
||||
|
||||
@@ -293,8 +293,13 @@ CREATE TABLE IF NOT EXISTS precise_movements (
|
||||
);
|
||||
CREATE VIEW IF NOT EXISTS position_units AS
|
||||
SELECT p.account,p.market,p.outcome,p.available*1000000+COALESCE(r.micros,0) AS available,
|
||||
p.reserved*1000000 AS reserved,p.phase,p.payout_per_share
|
||||
p.reserved*10000 AS reserved,p.phase,p.payout_per_share
|
||||
FROM position_sizes p LEFT JOIN position_remainders r USING(account,market,outcome);
|
||||
CREATE VIEW IF NOT EXISTS market_backing AS
|
||||
SELECT m.id AS market,m.collateral*10000+COALESCE(r.micros,0) AS micros
|
||||
FROM markets m LEFT JOIN collateral_remainders r ON r.market=m.id;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS budget_spend_micros (
|
||||
order_seq INTEGER PRIMARY KEY REFERENCES budget_buys(order_seq),
|
||||
micros INTEGER NOT NULL CHECK(micros>=0)
|
||||
);
|
||||
|
||||
@@ -82,11 +82,7 @@ impl LimitAmounts {
|
||||
let tick = TickSize::load(db, &self.market)?
|
||||
.ok_or_else(|| anyhow::anyhow!("listed market with configured tick_size required"))?;
|
||||
tick.check(self.price_micros)?;
|
||||
ensure!(
|
||||
(10_000..=1_000_000_000_000_000).contains(&self.size_micros),
|
||||
"invalid share size"
|
||||
);
|
||||
let shares = self.size_micros / 10_000 * 10_000;
|
||||
let shares = crate::lots::amount(None, Some(self.size_micros))? * crate::lots::MICROS;
|
||||
if let Some(minimum) = MinimumSize::load(db, &self.market)? {
|
||||
minimum.check_microshares(shares)?;
|
||||
}
|
||||
@@ -100,7 +96,7 @@ impl LimitAmounts {
|
||||
json!({"asset_id":assets::id(&self.market,&self.outcome),"tick_size":tick.text(),
|
||||
"price_micros":self.price_micros,"size_micros":shares,"collateral_micros":collateral,
|
||||
"makerAmount":maker.to_string(),"takerAmount":taker.to_string(),
|
||||
"local_precision_supported":self.price_micros%10000==0 && shares%1_000_000==0}),
|
||||
"local_precision_supported":self.price_micros%10000==0}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,11 +4,22 @@ use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn serialize_hundredths<S: serde::Serializer>(
|
||||
value: &i64,
|
||||
serializer: S,
|
||||
) -> std::result::Result<S::Ok, S::Error> {
|
||||
crate::lots::display(*value).serialize(serializer)
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize)]
|
||||
struct Totals {
|
||||
#[serde(serialize_with = "serialize_hundredths")]
|
||||
matched_shares: i64,
|
||||
#[serde(serialize_with = "serialize_hundredths")]
|
||||
taker_shares: i64,
|
||||
#[serde(serialize_with = "serialize_hundredths")]
|
||||
taker_notional_cents: i64,
|
||||
#[serde(serialize_with = "serialize_hundredths")]
|
||||
unknown_role_shares: i64,
|
||||
}
|
||||
|
||||
@@ -30,6 +41,7 @@ impl Totals {
|
||||
pub(crate) struct Volume {
|
||||
all_time: Totals,
|
||||
last_24h: Totals,
|
||||
#[serde(serialize_with = "serialize_hundredths")]
|
||||
unknown_time_shares: i64,
|
||||
}
|
||||
|
||||
|
||||
@@ -1118,29 +1118,29 @@ fn cash_buy_reconciles_direct_and_complementary_depth_with_an_exact_budget() {
|
||||
assert_eq!(state(&mut e), before);
|
||||
}
|
||||
let receipt = e.execute(request.clone()).unwrap();
|
||||
assert_eq!(receipt["spent_cents"], 160);
|
||||
assert_eq!(receipt["unspent_cents"], 10);
|
||||
assert_eq!(receipt["filled"], 4);
|
||||
assert_eq!(receipt["spent_cents"].to_string(), "169.9");
|
||||
assert_eq!(receipt["unspent_cents"].to_string(), "0.1");
|
||||
assert_eq!(receipt["filled"].to_string(), "4.22");
|
||||
assert_eq!(receipt["status"], "cancelled");
|
||||
drop(e);
|
||||
let mut e = Exchange::open(path).unwrap();
|
||||
assert_eq!(e.execute(request).unwrap(), receipt);
|
||||
let s = state(&mut e);
|
||||
assert_eq!(s["accounts"][2]["cash"], 10);
|
||||
assert_eq!(s["accounts"][2]["cash"], 0);
|
||||
assert_eq!(s["paired_fills"][0]["kind"], "mint");
|
||||
assert_eq!(s["markets"][0]["collateral"], 1200);
|
||||
assert_eq!(s["markets"][0]["collateral"], 1222);
|
||||
let lookup = e
|
||||
.execute(json!({"op":"open_orders","account":"buyer","order":receipt["order"]}))
|
||||
.unwrap();
|
||||
assert_eq!(lookup["orders"][0]["spent_cents"], 160);
|
||||
assert_eq!(lookup["orders"][0]["spent_cents"].to_string(), "169.9");
|
||||
assert_eq!(lookup["orders"][0]["open_size"], 0);
|
||||
let fok = e
|
||||
.execute(
|
||||
json!({"op":"market_buy","id":"exact","market":"e","outcome":"YES",
|
||||
"account":"bob","amount_cents":45,"max_price":45,"tif":"FOK"}),
|
||||
"account":"bob","amount_cents":27,"max_price":45,"tif":"FOK"}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(fok["spent_cents"], 45);
|
||||
assert_eq!(fok["spent_cents"], 27);
|
||||
assert_eq!(fok["status"], "filled");
|
||||
}
|
||||
|
||||
@@ -1878,7 +1878,9 @@ fn fees_follow_taker_cash_budget_and_net_sale_proceeds() {
|
||||
}
|
||||
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" if cmd["amount_cents"] == 5000 => {
|
||||
assert_eq!(reply["filled_shares"].to_string(), "97.56")
|
||||
}
|
||||
"estimate" => assert_eq!(reply["fee_micros"], 1250000),
|
||||
"market_buy" => {
|
||||
assert_eq!(reply["total_spent_micros"], 51250000);
|
||||
@@ -2052,7 +2054,7 @@ fn minimum_size_checks_submitted_orders_and_preserves_partial_fills() {
|
||||
);
|
||||
e.execute(json!({"op":"open","id":"open-f","market":"f"}))
|
||||
.unwrap();
|
||||
for (budget, ok) in [(307, false), (308, true)] {
|
||||
for (budget, ok) in [(262, false), (263, true)] {
|
||||
let quote=e.execute(json!({"op":"estimate","market":"f","outcome":"YES","side":"buy","max_price":50,"amount_cents":budget}));
|
||||
assert_eq!(quote.is_ok(), ok);
|
||||
}
|
||||
@@ -2472,3 +2474,75 @@ fn half_payout_keeps_unpayable_base_unit_in_market_backing() {
|
||||
assert_eq!(s["settlement_dust"][0]["micros"], 1);
|
||||
assert_eq!(s["collateral_remainders"][0]["micros"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auction_fraction_survives_restart_then_trades_at_maker_price() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("lots.db");
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
for line in include_str!("../../../docs/examples/fractional-orders.jsonl").lines() {
|
||||
let request: Value = serde_json::from_str(line).unwrap();
|
||||
if request["op"] == "book" {
|
||||
drop(engine);
|
||||
engine = Exchange::open(&path).unwrap();
|
||||
}
|
||||
let reply = engine.execute(request.clone()).unwrap();
|
||||
match request["op"].as_str().unwrap() {
|
||||
"book" => assert_eq!(reply["asks"][0]["size"].to_string(), "0.73"),
|
||||
"cancel" => assert_eq!(reply["cancelled"].to_string(), "0.44"),
|
||||
"balance" => assert_eq!(reply["available_micros"], 1_565_500),
|
||||
"history" => {
|
||||
assert_eq!(reply["points"][0]["quantity"].to_string(), "0.5");
|
||||
assert_eq!(reply["points"][1]["quantity"].to_string(), "0.29");
|
||||
assert_eq!(reply["points"][1]["price_micros"], 550000);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let lookup = engine
|
||||
.execute(json!({"op":"open_orders","account":"maker","order":1}))
|
||||
.unwrap();
|
||||
assert_eq!(lookup["orders"][0]["size_matched"].to_string(), "0.79");
|
||||
assert_eq!(lookup["orders"][0]["original_size"].to_string(), "1.23");
|
||||
let pos = engine
|
||||
.execute(json!({"op":"positions","account":"maker","market":"e"}))
|
||||
.unwrap();
|
||||
let yes = pos["positions"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|p| p["outcome"] == "YES")
|
||||
.unwrap();
|
||||
assert_eq!(yes["available_size"].to_string(), "1.21");
|
||||
assert_eq!(yes["reserved_size"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_resting_order_is_scaled_once_and_keeps_fifo_after_partial_fill() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("old.db");
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
db.execute_batch(include_str!("../src/schema.sql")).unwrap();
|
||||
db.execute_batch(
|
||||
"INSERT INTO accounts VALUES('a',0),('b',100);
|
||||
INSERT INTO markets(id,rules,phase,collateral) VALUES('old','r','continuous',100);
|
||||
INSERT INTO positions VALUES('a','old','YES',0),('a','old','NO',1);
|
||||
INSERT INTO orders VALUES(17,'a','old','YES','sell',40,1,1,'live');",
|
||||
)
|
||||
.unwrap();
|
||||
drop(db);
|
||||
for _ in 0..2 {
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
assert_eq!(
|
||||
e.execute(json!({"op":"book","market":"old","outcome":"YES"}))
|
||||
.unwrap()["asks"][0]["size"],
|
||||
1
|
||||
);
|
||||
}
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
e.execute(json!({"op":"order","id":"hit","account":"b","market":"old","outcome":"YES","side":"buy","price":50,"size_micros":10000})).unwrap();
|
||||
let r = e
|
||||
.execute(json!({"op":"cancel","id":"release","account":"a","order":17}))
|
||||
.unwrap();
|
||||
assert_eq!(r["cancelled"].to_string(), "0.99");
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# matching
|
||||
|
||||
每个 OrderBook 保存一个交易品的常驻盘口。买卖双方各有一棵按价格、原始受理序号排序的 BTreeMap。每本簿的价格均用同一个最小价格步长的整数倍表示,数量单位为份。现有 exchange 以一美分为一步。exchange 按市场和结果持有这些簿,并把已提交的订单余量逐笔应用到对应的树。
|
||||
每个 OrderBook 保存一个交易品的常驻盘口。买卖双方各有一棵按价格、原始受理序号排序的 BTreeMap。每本簿的价格均用同一个最小价格步长的整数倍表示,数量用整数表示最小交易单位。exchange 的价格使用美分,每个数量单位为 0.01 份。exchange 按市场和结果持有这些簿,并把已提交的订单余量逐笔应用到对应的树。
|
||||
|
||||
## 文件依赖
|
||||
|
||||
@@ -24,8 +24,8 @@ sequenceDiagram
|
||||
B->>M: match_incoming,传入一条新订单
|
||||
M->>M: 从对手方最优价起遍历,同价按原序号分配
|
||||
else 盘中按金额买入
|
||||
B->>M: match_budget_buy,传入买单序号、最高价、以同一步长折算的总预算
|
||||
M->>M: 在同一卖盘上逐单扣减可用预算,末档取可负担的整份
|
||||
B->>M: match_budget_buy,传入买单序号、最高价、以美分乘数量单位折算的总预算
|
||||
M->>M: 在同一卖盘上逐单扣减可用预算,末档取预算可负担的最大整数单位数
|
||||
else 集合竞价
|
||||
B->>M: opening,在买一与卖一之间计算统一成交价
|
||||
M->>M: 从卖一起,只访问新的卖价或买价之后的第一个价格步长
|
||||
|
||||
@@ -42,8 +42,8 @@ impl OrderBook {
|
||||
}
|
||||
}
|
||||
|
||||
/// Buy whole shares at maker prices. Budget and limit use the instrument's
|
||||
/// integer tick unit (total cash in ticks and ticks per share respectively).
|
||||
/// Buy integer lots at maker prices. Express the budget in price ticks
|
||||
/// multiplied by quantity lots, the same units as price * remaining.
|
||||
pub fn match_budget_buy(&self, seq: i64, limit: i64, budget: i64) -> Vec<Fill> {
|
||||
let mut cash = budget;
|
||||
let mut capacity = i64::MAX;
|
||||
|
||||
@@ -10,6 +10,7 @@ pub struct Order {
|
||||
pub side: Side,
|
||||
/// Integer price ticks per share, in the same unit throughout this book.
|
||||
pub price: i64,
|
||||
/// Number of minimum quantity lots left on the book.
|
||||
pub remaining: i64,
|
||||
}
|
||||
|
||||
@@ -19,5 +20,6 @@ pub struct Fill {
|
||||
pub ask: i64,
|
||||
/// Integer price ticks per share, in the same unit throughout this book.
|
||||
pub price: i64,
|
||||
/// Executed lots, using the same scale as Order::remaining.
|
||||
pub quantity: i64,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{"op":"list","id":"match","market":"e","rules":"Official match result","tick_size":"0.01"}
|
||||
{"op":"fund","id":"maker","account":"maker","cents":200}
|
||||
{"op":"fund","id":"taker","account":"taker","cents":200}
|
||||
{"op":"split","id":"pairs","account":"maker","market":"e","qty":2}
|
||||
{"op":"order","id":"offer","market":"e","account":"maker","outcome":"YES","side":"sell","price":55,"size_micros":1239999}
|
||||
{"op":"order","id":"bid","market":"e","account":"taker","outcome":"YES","side":"buy","price":55,"size_micros":500000}
|
||||
{"op":"open","id":"kick","market":"e"}
|
||||
{"op":"book","asset_id":"eb:YES:e"}
|
||||
{"op":"order","id":"take","market":"e","account":"taker","outcome":"YES","side":"buy","price":56,"size_micros":290000,"tif":"FOK"}
|
||||
{"op":"cancel","id":"withdraw","account":"maker","order":1}
|
||||
{"op":"balance","account":"taker"}
|
||||
{"op":"history","market":"e","outcome":"YES","from_ms":0,"to_ms":9000000000000,"limit":20}
|
||||
@@ -105,7 +105,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 分三份,则成交 4.22 份,实付 169.90 分,退回 0.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)
|
||||
|
||||
@@ -199,7 +199,7 @@ FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高
|
||||
|
||||
上架时可显式配置 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 附加费与真实收费记录仍待对照。
|
||||
[可重放样例](examples/fees.jsonl)中,100 份 × 0.50,费率 0.05 时收 1.25。现金预算 50.00 能买 97.56 份;预算 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 附加费与真实收费记录仍待对照。
|
||||
|
||||
## 订单心跳与断线撤单
|
||||
|
||||
@@ -215,7 +215,7 @@ FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高
|
||||
|
||||
[可重放样例](examples/minimum-size.jsonl)上架时设置 min_order_size="5"。卖家挂 8 份,第一张 5 份买单成交后余下 3 份,仍可在盘口看到。第二张 FAK 买单给定预算 2.60 模拟美元、保护价 0.52,达到提交 5 份的门槛,可成交剩余 3 份。若改为 2.59 则在预留资金前拒绝。卖单和按份数发出的限价单检查提交份数;盘前、盘中、YES 与 NO 接受同一门槛。撤单、逐笔成交和存量余额沿用原有语义。
|
||||
|
||||
list 接受十进制份额字符串,最多六位小数;book、assets 和事件 catalog 返回去掉多余末尾零的字符串。没有配置的旧市场返回 null,继续适用原有数量与预算逻辑。本地只能交易整份,门槛 5.125 的最小可提交份数为 6。预算买单用保护价和这一起订份数计算最低预算,并计入该价位的一笔吃单费。例如保护价 0.50、费率 0.05 时,六份需要 3.075 模拟美元,分为单位的预算至少 3.08。这个含费门槛、部分成交余量与生产舍入方式仍待外场比对。
|
||||
list 接受十进制份额字符串,最多六位小数;book、assets 和事件 catalog 返回去掉多余末尾零的字符串。没有配置的旧市场返回 null,继续适用原有数量与预算逻辑。门槛 5.125 的最小可提交份数为 5.13。预算买单用保护价和这一起订份数计算最低预算,并计入该价位的一笔吃单费。例如保护价 0.50、费率 0.05 时,5.13 份按逐笔费用取整后需要 2.62913 模拟美元,整分预算至少 2.63。这个含费门槛、部分成交余量与生产舍入方式仍待外场比对。
|
||||
|
||||
## 下单面板的单笔与批量买卖报价
|
||||
|
||||
@@ -235,7 +235,7 @@ list 接受十进制份额字符串,最多六位小数;book、assets 和事
|
||||
|
||||
list 可传 tick_size 字符串。资产、盘口与赛事目录返回配置的步长。当前支持 0.1、0.01、0.005、0.0025、0.001、0.0001 美元。配置市场的委托价及市价单保护价必须在 [tick, 1−tick] 且为步长的整数倍。官方对 0.0025 的应用限定于指定世界杯盘型;模拟市场允许操作员配置六种网格,未按赛事资格过滤。上架后的步长可随本地 tick_size_change 命令更新。生产 WebSocket 订阅及资产映射仍待接入。未配置的旧盘返回 null,延续原有整分交易范围。[官方交易约束](https://docs.polymarket.com/market-data/market-details.md#trading-constraints)
|
||||
|
||||
[限价金额重放样例](examples/tick-size.jsonl)使用 Gamma 市场 559651 曾公开的 0.001 步长和 0.013 报价。limit_amounts 接收整数 price_micros 和 size_micros,后者向下取到百分之一份后检查最小份额。5.129999 份得到 5.12 份,抵押金额为 0.06656 模拟美元。买单的 makerAmount 为字符串 66560,takerAmount 为 5120000,卖单反向。回执的 local_precision_supported 仅描述价格和舍入后数量能否经现有整分、整份订单入口表示。预览不预留资金,不签名、不发送外场订单。官方六档的价格小数位数加两位份额精度均不超过六位,网格上的上述整数乘法可精确编码。[官方限价金额映射](https://docs.polymarket.com/trading/place-orders.md#limit-orders)
|
||||
[限价金额重放样例](examples/tick-size.jsonl)使用 Gamma 市场 559651 曾公开的 0.001 步长和 0.013 报价。limit_amounts 接收整数 price_micros 和 size_micros,后者向下取到百分之一份后检查最小份额。5.129999 份得到 5.12 份,抵押金额为 0.06656 模拟美元。买单的 makerAmount 为字符串 66560,takerAmount 为 5120000,卖单反向。回执的 local_precision_supported 仅描述价格和舍入后数量能否经现有整分价格、百分之一份的订单入口表示。预览不预留资金,不签名、不发送外场订单。官方六档的价格小数位数加两位份额精度均不超过六位,网格上的上述整数乘法可精确编码。[官方限价金额映射](https://docs.polymarket.com/trading/place-orders.md#limit-orders)
|
||||
|
||||
样例还包含一个步长 0.1 的本地集合竞价。50 分卖 2 份,对手分别以 50 分买 3 份、70 分买 2 份,开盘以 60 分成交 2 份。同一组订单若步长为 1 分,开盘价是 51 分。细于一分的市场目前只接受其与整分网格重合的本地委托价格。
|
||||
|
||||
@@ -257,4 +257,12 @@ book 的 tick_seq 与盘口快照同事务读取。客户端使用 tick_history
|
||||
|
||||
官方 split 和 merge 接受六位小数的整数基本单位。Eventbook 的两种请求都可传 qty_micros,一个单位等于百万分之一对 YES/NO;原有 qty 仍按整份解释。两者择一。现金、市场抵押和两个结果资产在一个 SQLite 事务内更新。旧账本按零余数读取。同一结果的可卖整份和小数尾数属于同一个仓位,挂卖占用的份额在撤单后才能合并。[官方持仓接口](https://docs.polymarket.com/trading/positions/manage.md)
|
||||
|
||||
[重放样例](examples/fractional-inventory.jsonl)用 1.500001 模拟美元拆出等量 YES 和 NO,预留 1 YES 后最多能合并 0.500001 对。以 YES 裁决后,单账户兑付与钱包活动均保留六位精度。VOID 在本地按每个结果余额单独计算一半,向下取到最小现金单位,未兑出的尾差保留在市场抵押并记入 settlement_dust。该取整顺序与 Gnosis CTF 的 redeemPositions 源码一致。Polymarket 生产部署和 Protocol V2 的尾差样本仍需分别核验。连续撮合、集合竞价和负风险转换目前仍接受整份数量。[CTF 参考合约](https://github.com/gnosis/conditional-tokens-contracts/blob/master/contracts/ConditionalTokens.sol#L202-L225)
|
||||
[重放样例](examples/fractional-inventory.jsonl)用 1.500001 模拟美元拆出等量 YES 和 NO,预留 1 YES 后最多能合并 0.500001 对。以 YES 裁决后,单账户兑付与钱包活动均保留六位精度。VOID 在本地按每个结果余额单独计算一半,向下取到最小现金单位,未兑出的尾差保留在市场抵押并记入 settlement_dust。该取整顺序与 Gnosis CTF 的 redeemPositions 源码一致。Polymarket 生产部署和 Protocol V2 的尾差样本仍需分别核验。负风险转换目前仍接受整份数量。[CTF 参考合约](https://github.com/gnosis/conditional-tokens-contracts/blob/master/contracts/ConditionalTokens.sol#L202-L225)
|
||||
|
||||
## 百分之一份委托
|
||||
|
||||
order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可以用 qty 表示整份。输入 1,239,999 微份会截为 1.23 份,再检查市场门槛。整分报价下,每一笔成交金额都能精确换算为微美元。实际分配、资金或份额预留、部分成交撤单、互补成交与重启恢复共用一个数量单位。预算买入也能吃到部分份额。以 0.52 报价的现金市单在官方文档中可编码到四位小数份额;目前模拟预算买单的执行粒度为 0.01 份,细于一分的报价仍只可预览。[官方委托精度与市价单样例](https://docs.polymarket.com/trading/place-orders.md)
|
||||
|
||||
[可重放样例](examples/fractional-orders.jsonl)中,1.239999 份委托按 1.23 份入簿。开盘成交 0.50 份,盘中成交 0.29 份,剩余 0.44 份可撤回。
|
||||
|
||||
升级已有 SQLite 文件前须停止使用旧版的所有进程。首次用新版打开时,订单、普通成交、互补成交和成交曲线中的历史数量在同一写事务内乘以 100,旧回执保持原文。同一文件由多个新版进程打开时只转换一次。升级后的文件不能与按整份解释原始列的旧程序共用。
|
||||
|
||||
Reference in New Issue
Block a user