Encode market order amounts and enforce rounded buy protection

This commit is contained in:
2026-12-03 07:12:31 +08:00
parent 20ce08adf9
commit f90605bfc7
12 changed files with 290 additions and 18 deletions
+1
View File
@@ -69,6 +69,7 @@ pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
| "market_sell"
| "estimate"
| "limit_amounts"
| "market_amounts"
| "tick_history"
| "tick_size_change"
| "market_buy"
+8 -2
View File
@@ -201,8 +201,11 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
minimum.check_budget(amount_cents, max_price, rate)?;
}
crate::tick_size::validate(
crate::tick_size::TickSize::load(tx, &market)?.as_ref(),
let tick = crate::tick_size::TickSize::load(tx, &market)?;
let amounts = crate::market_amounts::Amounts::for_order(
tick.as_ref(),
Side::Buy,
amount_cents,
max_price,
)?;
ledger::cash(tx, &account, -amount_cents)?;
@@ -248,6 +251,9 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
"cancelled"
};
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 let Some(amounts) = amounts {
receipt["order_amounts"] = amounts.json();
}
if fee > 0 || spent % 10000 != 0 {
receipt["fee_micros"] = json!(fee);
receipt["unspent_micros"] = json!(unspent_micros);
+2
View File
@@ -236,6 +236,7 @@ impl Listing {
pub(crate) enum Query {
Estimate(crate::estimate::Request),
LimitAmounts(crate::tick_size::LimitAmounts),
MarketAmounts(crate::market_amounts::Request),
TickHistory(crate::tick_changes::History),
PricesHistory(crate::prices_history::Request),
QuoteHistory(crate::quotes::Filter),
@@ -307,6 +308,7 @@ impl Query {
Self::QuoteHistory(request) => request.read(db),
Self::PricesHistory(request) => request.read(db),
Self::TickHistory(request) => request.read(db),
Self::MarketAmounts(request) => request.read(db),
Self::LimitAmounts(request) => request.read(db),
Self::Estimate(request) => request.read(db, books),
Self::Resolution { market } => crate::resolution::read(db, &market),
+2 -1
View File
@@ -98,7 +98,8 @@ pub(crate) enum Command {
outcome: String,
account: String,
key_id: Option<String>,
amount_cents: i64,
amount_cents: Option<i64>,
amount_micros: Option<i64>,
max_price: Option<i64>,
max_price_micros: Option<i64>,
tif: Option<TimeInForce>,
+10 -13
View File
@@ -1,10 +1,4 @@
use crate::{
assets,
book::gross_micros,
command::TimeInForce,
resident::Books,
validation::{amount, phase},
};
use crate::{assets, book::gross_micros, command::TimeInForce, resident::Books, validation::phase};
use anyhow::{ensure, Result};
use matching::{Order, Side};
use rusqlite::Transaction;
@@ -17,7 +11,8 @@ pub(crate) enum Request {
Buy {
market: String,
outcome: String,
amount_cents: i64,
amount_cents: Option<i64>,
amount_micros: Option<i64>,
max_price: Option<i64>,
max_price_micros: Option<i64>,
tif: Option<TimeInForce>,
@@ -40,6 +35,7 @@ impl Request {
market,
outcome,
amount_cents,
amount_micros,
max_price,
max_price_micros,
tif,
@@ -47,7 +43,7 @@ impl Request {
market,
outcome,
Side::Buy,
amount_cents,
crate::market_amounts::cash_cents(amount_cents, amount_micros)?,
crate::tick_size::input(max_price, max_price_micros)?,
tif,
),
@@ -76,9 +72,6 @@ impl Request {
edge
});
let tif = tif.unwrap_or(TimeInForce::Fak);
if side == Side::Buy {
amount(requested)?;
}
ensure!(
matches!(tif, TimeInForce::Fak | TimeInForce::Fok),
"estimate requires FAK or FOK"
@@ -88,7 +81,8 @@ impl Request {
&& (0..=crate::tick_size::PAR).contains(&limit),
"invalid outcome or price"
);
crate::tick_size::validate(tick.as_ref(), limit)?;
let amounts =
crate::market_amounts::Amounts::for_order(tick.as_ref(), side, requested, limit)?;
phase(tx, &market, &["continuous"])?;
let rate = crate::fees::rate(tx, &market)?;
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
@@ -133,6 +127,9 @@ impl Request {
"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)});
if let Some(amounts) = amounts {
result["order_amounts"] = amounts.json();
}
match side {
Side::Buy => {
result["total_spent_micros"] = json!(gross + fee);
+2
View File
@@ -21,6 +21,7 @@ mod kickoff;
mod ledger;
mod lots;
mod market;
mod market_amounts;
mod minimum_size;
mod neg_risk;
mod open_interest;
@@ -112,6 +113,7 @@ impl Exchange {
"assets"
| "estimate"
| "limit_amounts"
| "market_amounts"
| "tick_history"
| "catalog"
| "events"
+14 -2
View File
@@ -179,6 +179,14 @@ pub(crate) fn apply(
"market sell requires FAK or FOK"
);
let qty = crate::lots::amount(qty, size_micros)?;
let price = crate::tick_size::required(min_price, min_price_micros)?;
let tick = crate::tick_size::TickSize::load(tx, &market)?;
let amounts = crate::market_amounts::Amounts::for_order(
tick.as_ref(),
matching::Side::Sell,
qty,
price,
)?;
let result = book::submit(
tx,
books,
@@ -188,7 +196,7 @@ pub(crate) fn apply(
key_id,
outcome,
side: "sell".to_owned(),
price: crate::tick_size::required(min_price, min_price_micros)?,
price,
qty,
tif,
expiration: None,
@@ -196,6 +204,9 @@ pub(crate) fn apply(
},
)?;
let mut receipt = result.receipt();
if let Some(amounts) = amounts {
receipt["order_amounts"] = amounts.json();
}
receipt["proceeds_cents"] =
json!(crate::inventory::decimal(result.gross_micros.into(), 10000));
receipt["unsold_shares"] = json!(crate::lots::display(qty - result.filled));
@@ -210,6 +221,7 @@ pub(crate) fn apply(
account,
key_id,
amount_cents,
amount_micros,
max_price,
max_price_micros,
tif,
@@ -221,7 +233,7 @@ pub(crate) fn apply(
outcome,
account,
key_id,
amount_cents,
amount_cents: crate::market_amounts::cash_cents(amount_cents, amount_micros)?,
max_price: crate::tick_size::required(max_price, max_price_micros)?,
tif: tif.unwrap_or(crate::command::TimeInForce::Fak),
},
+146
View File
@@ -0,0 +1,146 @@
use crate::{assets, lots, minimum_size::MinimumSize, tick_size::TickSize};
use anyhow::{ensure, Result};
use matching::Side;
use rusqlite::Connection;
use serde::Deserialize;
use serde_json::{json, Value};
pub(crate) fn cash_cents(cents: Option<i64>, micros: Option<i64>) -> Result<i64> {
let cents = match (cents, micros) {
(Some(n), None) => n,
(None, Some(n)) if n > 0 => n / 10_000,
_ => anyhow::bail!("provide one positive amount_cents or amount_micros"),
};
crate::validation::amount(cents)?;
Ok(cents)
}
pub(crate) struct Amounts {
maker: i64,
taker: i64,
}
impl Amounts {
pub fn for_order(
tick: Option<&TickSize>,
side: Side,
requested: i64,
price_units: i64,
) -> Result<Option<Self>> {
match tick {
Some(tick) => Self::encode(
tick,
side,
requested,
price_units * crate::tick_size::PRICE_MICROS,
)
.map(Some),
None => {
crate::tick_size::validate(None, price_units)?;
Ok(None)
}
}
}
// requested is in whole cents for BUY, 0.01-share lots for SELL.
fn encode(tick: &TickSize, side: Side, requested: i64, price: i64) -> Result<Self> {
tick.check(price)?;
let maker = requested
.checked_mul(10_000)
.ok_or_else(|| anyhow::anyhow!("order amount overflow"))?;
ensure!(maker > 0, "positive order amount required");
let scale = 1_000_000_i128;
let taker = match side {
Side::Buy => {
let quantum = match tick.0 {
100_000 => 1000,
10_000 => 100,
5_000 | 1_000 => 10,
2_500 | 100 => 1,
_ => anyhow::bail!("unsupported market tick"),
};
let cash = i128::from(maker) * scale;
let shares = cash / i128::from(price) / quantum * quantum;
ensure!(
cash < shares * i128::from(price + 100),
"rounded market buy exceeds price protection"
);
shares
}
Side::Sell => i128::from(maker) * i128::from(price) / scale,
};
Ok(Self {
maker,
taker: i64::try_from(taker)?,
})
}
pub fn json(&self) -> Value {
json!({"makerAmount": self.maker.to_string(), "takerAmount": self.taker.to_string()})
}
}
#[derive(Deserialize)]
#[serde(tag = "side", rename_all = "lowercase", deny_unknown_fields)]
pub(crate) enum Request {
Buy {
market: String,
outcome: String,
price_micros: i64,
amount_cents: Option<i64>,
amount_micros: Option<i64>,
},
Sell {
market: String,
outcome: String,
price_micros: i64,
qty: Option<i64>,
size_micros: Option<i64>,
},
}
impl Request {
pub fn read(self, db: &Connection) -> Result<Value> {
let (market, outcome, side, requested, price) = match self {
Self::Buy {
market,
outcome,
price_micros,
amount_cents,
amount_micros,
} => (
market,
outcome,
Side::Buy,
cash_cents(amount_cents, amount_micros)?,
price_micros,
),
Self::Sell {
market,
outcome,
price_micros,
qty,
size_micros,
} => (
market,
outcome,
Side::Sell,
lots::amount(qty, size_micros)?,
price_micros,
),
};
ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome");
let tick = TickSize::load(db, &market)?
.ok_or_else(|| anyhow::anyhow!("listed market with configured tick_size required"))?;
let amounts = Amounts::encode(&tick, side, requested, price)?;
if let Some(minimum) = MinimumSize::load(db, &market)? {
minimum.check_microshares(match side {
Side::Buy => amounts.taker,
Side::Sell => amounts.maker,
})?;
}
let mut result = amounts.json();
result["asset_id"] = json!(assets::id(&market, &outcome));
result["tick_size"] = json!(tick.text());
Ok(result)
}
}