use crate::amount::Amount;
use crate::error::{Error, ErrorBody, Result};
use crate::models_gen::{
BatchOrderResult, CancelBatchItem, CancelBatchResult, ErrorCode, Fill, Order, OrderSide,
OrderStatus, OrderType, TimeInForce, TriggerDirection,
};
pub const MAX_BATCH_ORDERS: usize = 20;
pub const MAX_CANCEL_ENTRIES: usize = 50;
#[derive(Debug, Clone, PartialEq)]
pub struct BatchOrderInput {
pub side: OrderSide,
pub r#type: OrderType,
pub client_order_id: Option<String>,
pub price: Option<Amount>,
pub quantity: Option<Amount>,
pub quote_quantity: Option<Amount>,
pub stop_price: Option<Amount>,
pub time_in_force: Option<TimeInForce>,
pub trigger_direction: Option<TriggerDirection>,
}
impl BatchOrderInput {
pub fn new(side: OrderSide, r#type: OrderType) -> Self {
BatchOrderInput {
side,
r#type,
client_order_id: None,
price: None,
quantity: None,
quote_quantity: None,
stop_price: None,
time_in_force: None,
trigger_direction: None,
}
}
}
impl CancelBatchItem {
pub fn by_order_id(order_id: impl Into<String>) -> Self {
CancelBatchItem {
order_id: Some(order_id.into()),
client_order_id: None,
}
}
pub fn by_client_order_id(client_order_id: impl Into<String>) -> Self {
CancelBatchItem {
order_id: None,
client_order_id: Some(client_order_id.into()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlaceOutcome {
Placed,
Failed,
Recovered,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CancelOutcome {
Cancelled,
Failed,
Recovered,
Unknown,
}
#[derive(Debug, Clone, PartialEq)]
pub struct BatchOrderOutcome {
pub index: i64,
pub client_order_id: String,
pub outcome: PlaceOutcome,
pub order_id: Option<String>,
pub status: Option<OrderStatus>,
pub order: Option<Order>,
pub fills: Vec<Fill>,
pub error: Option<ErrorBody>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct BatchPlaceResult {
pub results: Vec<BatchOrderOutcome>,
pub placed: usize,
pub failed: usize,
pub unknown: usize,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CancelEntryOutcome {
pub index: i64,
pub outcome: CancelOutcome,
pub order_id: Option<String>,
pub client_order_id: Option<String>,
pub status: Option<OrderStatus>,
pub order: Option<Order>,
pub error: Option<ErrorBody>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct BatchCancelResult {
pub results: Vec<CancelEntryOutcome>,
pub cancelled: usize,
pub failed: usize,
pub unknown: usize,
}
pub(crate) fn valid_client_order_id(cid: &str) -> bool {
(1..=64).contains(&cid.len())
&& !is_dot_segment(cid)
&& cid
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.' | b':'))
}
fn is_dot_segment(id: &str) -> bool {
id == "." || id == ".."
}
pub fn new_client_order_id() -> String {
crate::transport::new_id()
}
pub(crate) fn check_place(orders: &[BatchOrderInput]) -> Result<()> {
if !(1..=MAX_BATCH_ORDERS).contains(&orders.len()) {
return Err(Error::config(format!(
"trading.place_orders takes 1 to {MAX_BATCH_ORDERS} orders, got {}",
orders.len()
)));
}
let mut seen = std::collections::HashSet::new();
for (i, o) in orders.iter().enumerate() {
let Some(cid) = &o.client_order_id else {
continue;
};
if !valid_client_order_id(cid) {
return Err(Error::config(format!(
"trading.place_orders: orders[{i}]: client_order_id must be 1 to 64 characters of A-Z a-z 0-9 _ - . :"
)));
}
if !seen.insert(cid.as_str()) {
return Err(Error::config(format!(
"trading.place_orders: orders[{i}]: client_order_id {cid:?} is used twice in this batch"
)));
}
}
Ok(())
}
pub(crate) fn check_cancel(entries: &[CancelBatchItem]) -> Result<Vec<CancelBatchItem>> {
if !(1..=MAX_CANCEL_ENTRIES).contains(&entries.len()) {
return Err(Error::config(format!(
"trading.cancel_orders takes 1 to {MAX_CANCEL_ENTRIES} entries, got {}",
entries.len()
)));
}
let nonempty = |v: &Option<String>| v.clone().filter(|s| !s.is_empty());
entries
.iter()
.enumerate()
.map(|(i, e)| match (nonempty(&e.order_id), nonempty(&e.client_order_id)) {
(Some(id), None) => Ok(CancelBatchItem::by_order_id(id)),
(None, Some(cid)) if is_dot_segment(&cid) => Err(Error::config(format!(
"trading.cancel_orders: orders[{i}]: client_order_id must not be \".\" or \"..\""
))),
(None, Some(cid)) => Ok(CancelBatchItem::by_client_order_id(cid)),
_ => Err(Error::config(format!(
"trading.cancel_orders: orders[{i}]: give exactly one of order_id and client_order_id"
))),
})
.collect()
}
pub(crate) fn place_from_result(r: BatchOrderResult, after_ambiguous: bool) -> BatchOrderOutcome {
let mut o = BatchOrderOutcome {
index: r.index,
client_order_id: r.client_order_id,
outcome: PlaceOutcome::Failed,
order_id: None,
status: None,
order: None,
fills: r.fills,
error: r.error,
};
match (r.order, &o.error) {
(Some(order), None) => {
o.outcome = PlaceOutcome::Placed;
o.order_id = Some(order.id.clone());
o.status = Some(order.status.clone());
o.order = Some(order);
}
(_, Some(err)) if after_ambiguous && err.code == ErrorCode::AlreadyExists => {
o.outcome = PlaceOutcome::Recovered;
o.order_id = err.detail_str("order_id").map(str::to_string);
o.status = detail_status(err);
o.fills = vec![];
}
(_, Some(err))
if err.code != ErrorCode::AlreadyExists
&& (err.detail_str("order_id").is_some() || err.code == ErrorCode::Internal) =>
{
o.outcome = PlaceOutcome::Recovered;
o.order_id = err.detail_str("order_id").map(str::to_string);
o.status = detail_status(err);
o.fills = vec![];
}
_ => {}
}
o
}
fn detail_status(err: &ErrorBody) -> Option<OrderStatus> {
err.detail_str("status")
.filter(|s| *s != "unknown")
.map(OrderStatus::from)
}
pub(crate) fn needs_lookup(o: &BatchOrderOutcome) -> bool {
o.outcome == PlaceOutcome::Recovered && (o.order_id.is_none() || o.status.is_none())
}
pub(crate) fn place_matches(sent: &[String], results: &[BatchOrderResult]) -> bool {
results.len() == sent.len()
&& results
.iter()
.zip(sent)
.enumerate()
.all(|(i, (r, cid))| r.index == i as i64 && &r.client_order_id == cid)
}
pub(crate) fn cancel_matches(sent: &[CancelBatchItem], results: &[CancelBatchResult]) -> bool {
let same = |echo: &Option<String>, sent: &Option<String>| {
sent.is_none() || echo.is_none() || echo == sent
};
results.len() == sent.len()
&& results.iter().zip(sent).enumerate().all(|(i, (r, e))| {
r.index == i as i64
&& same(&r.order_id, &e.order_id)
&& same(&r.client_order_id, &e.client_order_id)
})
}
pub(crate) fn cancel_from_result(
r: CancelBatchResult,
after_ambiguous: bool,
) -> CancelEntryOutcome {
let mut o = CancelEntryOutcome {
index: r.index,
outcome: CancelOutcome::Failed,
order_id: r.order_id,
client_order_id: r.client_order_id,
status: None,
order: None,
error: r.error,
};
match (r.order, &o.error) {
(Some(order), None) => {
o.outcome = CancelOutcome::Cancelled;
o.order_id = Some(order.id.clone());
o.status = Some(order.status.clone());
o.order = Some(order);
}
(_, Some(err)) if after_ambiguous && err.code == ErrorCode::InvalidState => {
o.outcome = CancelOutcome::Recovered;
}
_ => {}
}
o
}
pub(crate) fn place_result(results: Vec<BatchOrderOutcome>) -> BatchPlaceResult {
let placed = results
.iter()
.filter(|o| match o.outcome {
PlaceOutcome::Placed => true,
PlaceOutcome::Recovered => o.status != Some(OrderStatus::Rejected),
_ => false,
})
.count();
let unknown = results
.iter()
.filter(|o| o.outcome == PlaceOutcome::Unknown)
.count();
BatchPlaceResult {
failed: results.len() - placed - unknown,
results,
placed,
unknown,
}
}
pub(crate) fn cancel_result(results: Vec<CancelEntryOutcome>) -> BatchCancelResult {
let cancelled = results
.iter()
.filter(|o| match o.outcome {
CancelOutcome::Cancelled => true,
CancelOutcome::Recovered => o.status == Some(OrderStatus::Cancelled),
_ => false,
})
.count();
let unknown = results
.iter()
.filter(|o| o.outcome == CancelOutcome::Unknown)
.count();
BatchCancelResult {
failed: results.len() - cancelled - unknown,
results,
cancelled,
unknown,
}
}