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,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user