#![allow(unexpected_cfgs, clippy::useless_conversion)]
use pyo3::prelude::*;
use crate::order_book::Side;
use crate::python::ValidationError;
pyo3::create_exception!(
_core,
OrderError,
pyo3::exceptions::PyValueError,
"Raised when an order is rejected. Distinct from ValidationError because \
the causes differ in kind: a malformed scenario is a setup mistake, made \
once, whereas a rejected order is a market rule hit during a run -- a \
market order outside regular hours, or a size the book will not accept. \
Callers reasonably handle the two differently."
);
fn parse_side(side: &str) -> PyResult<Side> {
match side {
"buy" => Ok(Side::Buy),
"sell" => Ok(Side::Sell),
other => Err(ValidationError::new_err(format!(
"side must be \"buy\" or \"sell\", got {other:?}"
))),
}
}
fn side_name(side: Side) -> &'static str {
match side {
Side::Buy => "buy",
Side::Sell => "sell",
}
}
fn check_size(name: &str, value: f64) -> PyResult<()> {
if !(value > 0.0) || !value.is_finite() {
return Err(ValidationError::new_err(format!(
"{name} must be finite and greater than zero, got {value}"
)));
}
Ok(())
}
#[pyclass(name = "Fill", module = "tradefloor._core", frozen, get_all)]
#[derive(Debug, Clone)]
pub struct PyFill {
pub price: f64,
pub quantity: f64,
pub maker_order_id: String,
pub maker_id: String,
pub taker_id: String,
pub taker_side: String,
}
#[pymethods]
impl PyFill {
fn __repr__(&self) -> String {
format!(
"Fill(price={}, quantity={}, taker_side={:?})",
self.price, self.quantity, self.taker_side
)
}
}
#[pyclass(name = "MatchResult", module = "tradefloor._core", frozen, get_all)]
#[derive(Debug, Clone)]
pub struct PyMatchResult {
pub fills: Vec<PyFill>,
pub unfilled: f64,
pub average_price: Option<f64>,
pub resting_order_id: Option<String>,
}
#[pymethods]
impl PyMatchResult {
fn __repr__(&self) -> String {
format!(
"MatchResult(fills={}, unfilled={}, average_price={:?})",
self.fills.len(),
self.unfilled,
self.average_price
)
}
}
#[pyclass(name = "PriceLevel", module = "tradefloor._core", frozen, get_all)]
#[derive(Debug, Clone, Copy)]
pub struct PyPriceLevel {
pub price: f64,
pub quantity: f64,
pub orders: u32,
}
#[pymethods]
impl PyPriceLevel {
fn __repr__(&self) -> String {
format!(
"PriceLevel(price={}, quantity={}, orders={})",
self.price, self.quantity, self.orders
)
}
}
#[pyclass(name = "SweepCost", module = "tradefloor._core", frozen, get_all)]
#[derive(Debug, Clone, Copy)]
pub struct PySweepCost {
pub average_price: f64,
pub worst_price: f64,
pub filled: f64,
}
#[pymethods]
impl PySweepCost {
fn __repr__(&self) -> String {
format!(
"SweepCost(average_price={}, worst_price={}, filled={})",
self.average_price, self.worst_price, self.filled
)
}
}
#[pyclass(name = "OrderBook", module = "tradefloor._core")]
pub struct PyOrderBook {
inner: crate::order_book::OrderBook,
}
impl PyOrderBook {
pub fn from_core(inner: crate::order_book::OrderBook) -> Self {
Self { inner }
}
}
#[pymethods]
impl PyOrderBook {
#[new]
#[pyo3(signature = (company_id, last_price = None))]
fn new(company_id: &str, last_price: Option<f64>) -> PyResult<Self> {
if let Some(p) = last_price {
check_size("last_price", p)?;
}
Ok(Self {
inner: crate::order_book::OrderBook::new(company_id, last_price),
})
}
#[pyo3(signature = (side, price, quantity, *, owner, order_id = None))]
fn post_limit(
&mut self,
side: &str,
price: f64,
quantity: f64,
owner: &str,
order_id: Option<String>,
) -> PyResult<String> {
let s = parse_side(side)?;
check_size("price", price)?;
check_size("quantity", quantity)?;
let company = self.inner.company_id.clone();
self.inner
.post_limit(s, price, quantity, owner, order_id)
.map(|o| o.id_in(&company))
.ok_or_else(|| OrderError::new_err("the book rejected the limit order"))
}
#[pyo3(signature = (
side, quantity, *, taker = "taker",
limit_price = None, post_remainder = false, order_id = None
))]
fn submit(
&mut self,
side: &str,
quantity: f64,
taker: &str,
limit_price: Option<f64>,
post_remainder: bool,
order_id: Option<String>,
) -> PyResult<PyMatchResult> {
let s = parse_side(side)?;
check_size("quantity", quantity)?;
if let Some(p) = limit_price {
check_size("limit_price", p)?;
}
let r = self.inner.submit(
s,
quantity,
taker,
crate::order_book::SubmitOptions {
limit_price,
post_remainder,
order_id,
skip_own: false,
house_ids: true,
},
);
Ok(PyMatchResult {
fills: r
.fills
.into_iter()
.map(|f| PyFill {
price: f.price,
quantity: f.quantity,
maker_order_id: f.maker_order_id,
maker_id: f.maker_id.into_owned(),
taker_id: f.taker_id.into_owned(),
taker_side: side_name(f.taker_side).to_string(),
})
.collect(),
unfilled: r.unfilled,
average_price: r.average_price,
resting_order_id: r.resting.map(|o| o.id_in(&self.inner.company_id)),
})
}
#[pyo3(signature = (side, price, quantity, *, owner))]
fn append_maker_level(
&mut self,
side: &str,
price: f64,
quantity: f64,
owner: &str,
) -> PyResult<Option<String>> {
let s = parse_side(side)?;
check_size("price", price)?;
check_size("quantity", quantity)?;
Ok(self
.inner
.append_maker_level(s, price, quantity, owner)
.map(|o| o.id_in(&self.inner.company_id)))
}
fn sweep_cost(&self, side: &str, quantity: f64) -> PyResult<Option<PySweepCost>> {
let s = parse_side(side)?;
check_size("quantity", quantity)?;
Ok(self.inner.sweep_cost(s, quantity).map(|c| PySweepCost {
average_price: c.average_price,
worst_price: c.worst_price,
filled: c.filled,
}))
}
#[pyo3(signature = (side, max_levels = 10))]
fn price_levels(&self, side: &str, max_levels: usize) -> PyResult<Vec<PyPriceLevel>> {
let s = parse_side(side)?;
Ok(self
.inner
.price_levels(s, max_levels)
.into_iter()
.map(|l| PyPriceLevel {
price: l.price,
quantity: l.quantity,
orders: l.orders,
})
.collect())
}
fn depth(&self, side: &str) -> PyResult<f64> {
Ok(self.inner.depth(parse_side(side)?))
}
fn cancel_order(&mut self, order_id: &str) -> bool {
self.inner.cancel_order(order_id)
}
fn cancel_all_for(&mut self, owner_id: &str) -> u32 {
self.inner.cancel_all_for(owner_id)
}
#[getter]
fn best_bid(&self) -> Option<f64> {
self.inner.best_bid()
}
#[getter]
fn best_ask(&self) -> Option<f64> {
self.inner.best_ask()
}
#[getter]
fn mid_price(&self) -> Option<f64> {
self.inner.mid_price()
}
#[getter]
fn spread(&self) -> Option<f64> {
self.inner.spread()
}
#[getter]
fn company_id(&self) -> String {
self.inner.company_id.clone()
}
fn __repr__(&self) -> String {
format!(
"OrderBook({:?}, bid={:?}, ask={:?})",
self.inner.company_id,
self.inner.best_bid(),
self.inner.best_ask()
)
}
}