154 lines
5.2 KiB
Rust
154 lines
5.2 KiB
Rust
use crate::{assets, inventory, minimum_size::MinimumSize, Exchange, MarketDataError};
|
|
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);
|
|
|
|
// A stored price is in 0.0001 dollars. One price unit times one order lot
|
|
// (0.01 shares) is exactly one cash micro.
|
|
pub(crate) const PAR: i64 = 10_000;
|
|
pub(crate) const PRICE_MICROS: i64 = 100;
|
|
pub(crate) fn input(cents: Option<i64>, micros: Option<i64>) -> Result<Option<i64>> {
|
|
match (cents, micros) {
|
|
(None, None) => Ok(None),
|
|
(Some(c), None) if (0..=100).contains(&c) => Ok(Some(c * 100)),
|
|
(None, Some(m)) if (0..=1_000_000).contains(&m) && m % PRICE_MICROS == 0 => {
|
|
Ok(Some(m / PRICE_MICROS))
|
|
}
|
|
_ => anyhow::bail!("provide one valid price in cents or micros"),
|
|
}
|
|
}
|
|
pub(crate) fn required(cents: Option<i64>, micros: Option<i64>) -> Result<i64> {
|
|
input(cents, micros)?.ok_or_else(|| anyhow::anyhow!("price required"))
|
|
}
|
|
pub(crate) fn validate(tick: Option<&TickSize>, price: i64) -> Result<()> {
|
|
if let Some(tick) = tick {
|
|
tick.check(price * PRICE_MICROS)
|
|
} else {
|
|
ensure!(
|
|
(0..=PAR).contains(&price) && price % 100 == 0,
|
|
"legacy market requires a whole-cent price"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
impl Exchange {
|
|
/// Current grid for a listed local outcome, including the whole-cent legacy grid.
|
|
pub fn minimum_tick_size(
|
|
&self,
|
|
token: &str,
|
|
) -> Result<Option<serde_json::Number>, MarketDataError> {
|
|
let (_, market) = assets::parse_id(token)
|
|
.map_err(|_| MarketDataError::Invalid("Invalid token id".into()))?;
|
|
let mut stmt = self.db.prepare_cached(
|
|
"SELECT s.step_micros FROM markets m LEFT JOIN market_tick_sizes s ON s.market=m.id WHERE m.id=?1"
|
|
)?;
|
|
let tick = stmt
|
|
.query_row([market], |r| r.get::<_, Option<i64>>(0))
|
|
.optional()?;
|
|
Ok(tick.map(|step| step.map(TickSize).unwrap_or(TickSize::WHOLE_CENT).number()))
|
|
}
|
|
}
|
|
|
|
impl TickSize {
|
|
pub(crate) const WHOLE_CENT: Self = Self(10_000);
|
|
|
|
pub(crate) fn number(&self) -> serde_json::Number {
|
|
inventory::decimal(self.0.into(), inventory::UNIT)
|
|
}
|
|
|
|
pub(crate) fn parse(value: &str) -> Result<Self> {
|
|
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"),
|
|
};
|
|
Ok(Self(micros))
|
|
}
|
|
|
|
pub fn configure(tx: &Transaction, market: &str, value: &str) -> Result<()> {
|
|
let micros = Self::parse(value)?.0;
|
|
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 {
|
|
self.number().to_string()
|
|
}
|
|
|
|
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 {
|
|
NonZeroU32::new((self.0 / PRICE_MICROS) 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)?;
|
|
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)?;
|
|
}
|
|
// 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":true}),
|
|
)
|
|
}
|
|
}
|