Validate market tick sizes and encode precise limit order amounts
This commit is contained in:
@@ -44,6 +44,8 @@ pub(crate) fn market_assets(db: &Connection, market: &str) -> Result<Value> {
|
||||
Ok(detail)
|
||||
},
|
||||
)?;
|
||||
detail["tick_size"] =
|
||||
json!(crate::tick_size::TickSize::load(db, market)?.map(|tick| tick.text()));
|
||||
detail["min_order_size"] =
|
||||
json!(crate::minimum_size::MinimumSize::load(db, market)?.map(|size| size.text()));
|
||||
detail["taker_fee_rate_ppm"] = json!(crate::fees::rate(db, market)?);
|
||||
@@ -66,6 +68,7 @@ pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
|
||||
| "trades"
|
||||
| "market_sell"
|
||||
| "estimate"
|
||||
| "limit_amounts"
|
||||
| "market_buy"
|
||||
| "cancel_market_orders"
|
||||
)
|
||||
|
||||
@@ -74,6 +74,9 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
|
||||
minimum.check_shares(qty)?;
|
||||
}
|
||||
if let Some(tick) = crate::tick_size::TickSize::load(tx, &market)? {
|
||||
tick.check(price * 10000)?;
|
||||
}
|
||||
let deadline = match tif {
|
||||
TimeInForce::Gtd => {
|
||||
let expiration =
|
||||
@@ -190,6 +193,9 @@ 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)?;
|
||||
}
|
||||
if let Some(tick) = crate::tick_size::TickSize::load(tx, &market)? {
|
||||
tick.check(max_price * 10000)?;
|
||||
}
|
||||
ledger::cash(tx, &account, -amount_cents)?;
|
||||
tx.execute(
|
||||
"INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status)
|
||||
|
||||
@@ -235,6 +235,7 @@ impl Listing {
|
||||
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub(crate) enum Query {
|
||||
Estimate(crate::estimate::Request),
|
||||
LimitAmounts(crate::tick_size::LimitAmounts),
|
||||
PricesHistory(crate::prices_history::Request),
|
||||
QuoteHistory(crate::quotes::Filter),
|
||||
Price(crate::quotes::PriceRequest),
|
||||
@@ -304,6 +305,7 @@ impl Query {
|
||||
Self::Prices { requests } => crate::quotes::prices(db, &requests),
|
||||
Self::QuoteHistory(request) => request.read(db),
|
||||
Self::PricesHistory(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),
|
||||
Self::Assets { market } => assets::market_assets(db, &market),
|
||||
@@ -335,7 +337,8 @@ impl Query {
|
||||
let minimum =
|
||||
crate::minimum_size::MinimumSize::load(db, &market)?.map(|size| size.text());
|
||||
Ok(
|
||||
json!({"asset_id":assets::id(&market,&outcome),"market":market,"outcome":outcome,"phase":phase,"bids":bids,"asks":asks,"min_order_size":minimum}),
|
||||
json!({"asset_id":assets::id(&market,&outcome),"market":market,"outcome":outcome,"phase":phase,"bids":bids,"asks":asks,"min_order_size":minimum,
|
||||
"tick_size":crate::tick_size::TickSize::load(db,&market)?.map(|tick|tick.text())}),
|
||||
)
|
||||
}
|
||||
Self::Quote { market, outcome } => {
|
||||
@@ -398,10 +401,11 @@ impl Query {
|
||||
let mut stmt = db.prepare(
|
||||
"SELECT s.market,COALESCE(a.question,s.question),yes_label,no_label,terms,source,resolver,rules_version,
|
||||
m.rules,m.phase,COALESCE(a.name,group_title),group_order,n.group_id,n.ordinal,
|
||||
a.role,a.clarification,a.named_at,minimum.microshares
|
||||
a.role,a.clarification,a.named_at,minimum.microshares,tick.step_micros
|
||||
FROM listed_markets s JOIN markets m ON m.id=s.market
|
||||
LEFT JOIN neg_risk_members n ON n.market=s.market
|
||||
LEFT JOIN augmented_outcomes a ON a.market=s.market
|
||||
LEFT JOIN market_tick_sizes tick ON tick.market=s.market
|
||||
LEFT JOIN market_minimum_sizes minimum ON minimum.market=s.market
|
||||
WHERE event=? AND (a.role IS NULL OR a.role<>'placeholder') ORDER BY group_order,s.market"
|
||||
)?;
|
||||
@@ -426,6 +430,7 @@ impl Query {
|
||||
"augmented_role":r.get::<_,Option<String>>(14)?,
|
||||
"clarification":r.get::<_,Option<String>>(15)?,
|
||||
"named_at":r.get::<_,Option<i64>>(16)?,
|
||||
"tick_size":r.get::<_,Option<i64>>(18)?.map(|v|crate::tick_size::TickSize(v).text()),
|
||||
"min_order_size":r.get::<_,Option<i64>>(17)?.map(crate::minimum_size::MinimumSize::format_microshares),
|
||||
"source":r.get::<_,String>(5)?,
|
||||
"resolver":r.get::<_,String>(6)?,
|
||||
|
||||
@@ -14,6 +14,7 @@ pub(crate) enum Command {
|
||||
rules: String,
|
||||
taker_fee_rate_ppm: Option<i64>,
|
||||
min_order_size: Option<String>,
|
||||
tick_size: Option<String>,
|
||||
#[serde(default)]
|
||||
listing: Option<crate::catalog::Listing>,
|
||||
resolution: Option<crate::resolution::Policy>,
|
||||
|
||||
@@ -39,29 +39,18 @@ impl Request {
|
||||
amount_cents,
|
||||
max_price,
|
||||
tif,
|
||||
} => (
|
||||
market,
|
||||
outcome,
|
||||
Side::Buy,
|
||||
amount_cents,
|
||||
max_price.unwrap_or(100),
|
||||
tif,
|
||||
),
|
||||
} => (market, outcome, Side::Buy, amount_cents, max_price, tif),
|
||||
Self::Sell {
|
||||
market,
|
||||
outcome,
|
||||
qty,
|
||||
min_price,
|
||||
tif,
|
||||
} => (
|
||||
market,
|
||||
outcome,
|
||||
Side::Sell,
|
||||
qty,
|
||||
min_price.unwrap_or(0),
|
||||
tif,
|
||||
),
|
||||
} => (market, outcome, Side::Sell, qty, 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)?;
|
||||
ensure!(
|
||||
@@ -72,6 +61,9 @@ impl Request {
|
||||
matches!(outcome.as_str(), "YES" | "NO") && (0..=100).contains(&limit),
|
||||
"invalid outcome or price"
|
||||
);
|
||||
if let Some(tick) = tick {
|
||||
tick.check(limit * 10000)?;
|
||||
}
|
||||
phase(tx, &market, &["continuous"])?;
|
||||
let rate = crate::fees::rate(tx, &market)?;
|
||||
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
|
||||
|
||||
@@ -27,6 +27,7 @@ mod public_trades;
|
||||
mod quotes;
|
||||
mod resident;
|
||||
mod resolution;
|
||||
mod tick_size;
|
||||
use resident::Books;
|
||||
|
||||
use anyhow::{ensure, Context, Result};
|
||||
@@ -98,6 +99,7 @@ impl Exchange {
|
||||
Some(
|
||||
"assets"
|
||||
| "estimate"
|
||||
| "limit_amounts"
|
||||
| "catalog"
|
||||
| "events"
|
||||
| "history"
|
||||
|
||||
@@ -51,6 +51,7 @@ pub(crate) fn apply(
|
||||
resolution,
|
||||
taker_fee_rate_ppm,
|
||||
min_order_size,
|
||||
tick_size,
|
||||
} => {
|
||||
identifier(&market)?;
|
||||
ensure!(!rules.trim().is_empty(), "rules required");
|
||||
@@ -58,6 +59,9 @@ pub(crate) fn apply(
|
||||
"INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')",
|
||||
params![market, rules],
|
||||
)?;
|
||||
if let Some(tick) = tick_size {
|
||||
crate::tick_size::TickSize::configure(tx, &market, &tick)?;
|
||||
}
|
||||
if let Some(size) = min_order_size {
|
||||
crate::minimum_size::MinimumSize::configure(tx, &market, &size)?;
|
||||
}
|
||||
@@ -261,7 +265,9 @@ pub(crate) fn apply(
|
||||
let book = books
|
||||
.get(&market, &outcome)
|
||||
.ok_or_else(|| anyhow::anyhow!("missing auction book"))?;
|
||||
book::settle(tx, &market, &outcome, book.opening(), None)?;
|
||||
let step = crate::tick_size::TickSize::load(tx, &market)?
|
||||
.map_or(std::num::NonZeroU32::MIN, |tick| tick.local_step());
|
||||
book::settle(tx, &market, &outcome, book.opening_with_step(step), None)?;
|
||||
}
|
||||
tx.execute("UPDATE markets SET phase='continuous' WHERE id=?", [market])?;
|
||||
Ok(json!({"phase":"continuous"}))
|
||||
|
||||
@@ -58,8 +58,12 @@ impl MinimumSize {
|
||||
}
|
||||
|
||||
pub fn check_shares(&self, qty: i64) -> Result<()> {
|
||||
self.check_microshares(qty * SCALE)
|
||||
}
|
||||
|
||||
pub fn check_microshares(&self, shares: i64) -> Result<()> {
|
||||
ensure!(
|
||||
qty * SCALE >= self.0,
|
||||
shares >= self.0,
|
||||
"order is below min_order_size of {} shares",
|
||||
self.text()
|
||||
);
|
||||
|
||||
@@ -260,3 +260,8 @@ CREATE TABLE IF NOT EXISTS market_minimum_sizes (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id),
|
||||
microshares INTEGER NOT NULL CHECK(microshares BETWEEN 1 AND 1000000000000000)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS market_tick_sizes (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id),
|
||||
step_micros INTEGER NOT NULL CHECK(step_micros IN (100000,10000,5000,2500,1000,100))
|
||||
);
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
use crate::{assets, minimum_size::MinimumSize};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::num::NonZeroU32;
|
||||
|
||||
pub(crate) struct TickSize(pub i64);
|
||||
|
||||
impl TickSize {
|
||||
pub fn configure(tx: &Transaction, market: &str, value: &str) -> Result<()> {
|
||||
let micros = match value.trim_end_matches('0') {
|
||||
"0.1" => 100_000,
|
||||
"0.01" => 10_000,
|
||||
"0.005" => 5_000,
|
||||
"0.0025" => 2_500,
|
||||
"0.001" => 1_000,
|
||||
"0.0001" => 100,
|
||||
_ => anyhow::bail!("unsupported tick_size"),
|
||||
};
|
||||
tx.execute(
|
||||
"INSERT INTO market_tick_sizes(market,step_micros) VALUES(?,?)",
|
||||
params![market, micros],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load(db: &Connection, market: &str) -> Result<Option<Self>> {
|
||||
Ok(db
|
||||
.prepare_cached("SELECT step_micros FROM market_tick_sizes WHERE market=?")?
|
||||
.query_row([market], |r| Ok(Self(r.get(0)?)))
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn text(&self) -> String {
|
||||
format!("0.{:06}", self.0).trim_end_matches('0').to_owned()
|
||||
}
|
||||
|
||||
pub fn check(&self, price: i64) -> Result<()> {
|
||||
ensure!(
|
||||
(self.0..=1_000_000 - self.0).contains(&price) && price % self.0 == 0,
|
||||
"price outside trading range or off tick_size {}",
|
||||
self.text()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn local_step(&self) -> NonZeroU32 {
|
||||
// Each supported sub-cent step divides one cent exactly.
|
||||
NonZeroU32::new((self.0 / 10_000).max(1) as u32).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum Side {
|
||||
Buy,
|
||||
Sell,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct LimitAmounts {
|
||||
market: String,
|
||||
outcome: String,
|
||||
side: Side,
|
||||
price_micros: i64,
|
||||
size_micros: i64,
|
||||
}
|
||||
|
||||
impl LimitAmounts {
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
ensure!(
|
||||
matches!(self.outcome.as_str(), "YES" | "NO"),
|
||||
"invalid outcome"
|
||||
);
|
||||
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;
|
||||
if let Some(minimum) = MinimumSize::load(db, &self.market)? {
|
||||
minimum.check_microshares(shares)?;
|
||||
}
|
||||
// Every supported step times 0.01 shares is an integer number of micros.
|
||||
let collateral = i128::from(self.price_micros) * i128::from(shares) / 1_000_000;
|
||||
let (maker, taker) = match self.side {
|
||||
Side::Buy => (collateral, i128::from(shares)),
|
||||
Side::Sell => (i128::from(shares), collateral),
|
||||
};
|
||||
Ok(
|
||||
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}),
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user