rustrade_execution/order/request.rs
1use crate::{
2 error::OrderError,
3 market::MarketSnapshot,
4 order::{
5 OrderEvent, OrderKind, TimeInForce,
6 id::{PositionId, VenueOrderId},
7 state::Cancelled,
8 },
9};
10use derive_more::Constructor;
11use rust_decimal::Decimal;
12use rustrade_instrument::{
13 Side,
14 asset::{AssetIndex, name::AssetNameExchange},
15 exchange::{ExchangeId, ExchangeIndex},
16 instrument::{InstrumentIndex, name::InstrumentNameExchange},
17};
18use serde::{Deserialize, Serialize};
19
20pub type OrderRequestOpen<ExchangeKey = ExchangeIndex, InstrumentKey = InstrumentIndex> =
21 OrderEvent<RequestOpen, ExchangeKey, InstrumentKey>;
22
23pub type OrderRequestCancel<ExchangeKey = ExchangeIndex, InstrumentKey = InstrumentIndex> =
24 OrderEvent<RequestCancel, ExchangeKey, InstrumentKey>;
25
26pub type OrderResponseCancel<
27 ExchangeKey = ExchangeIndex,
28 AssetKey = AssetIndex,
29 InstrumentKey = InstrumentIndex,
30> = OrderEvent<Result<Cancelled, OrderError<AssetKey, InstrumentKey>>, ExchangeKey, InstrumentKey>;
31
32pub type UnindexedOrderResponseCancel =
33 OrderResponseCancel<ExchangeId, AssetNameExchange, InstrumentNameExchange>;
34
35/// Parameters for opening a new order.
36///
37/// # Warning: `reduce_only` Default Behavior
38///
39/// The `reduce_only` field defaults to `false`, which means:
40/// - A `Sell` order defaults to `SellToOpen` (open short / write option)
41/// - A `Buy` order defaults to `BuyToOpen` (open long)
42///
43/// **For closing positions, callers MUST explicitly set `reduce_only: true`.**
44/// Failure to do so on non-crypto instruments (equities, options) will:
45/// - On non-margin accounts: result in a 422 rejection from the exchange
46/// - On margin accounts: silently open a short position instead of closing the long
47///
48/// The `close_open_positions_with_market_orders`
49/// helper sets this correctly. Direct `RequestOpen` construction must handle it manually.
50#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
51pub struct RequestOpen {
52 pub side: Side,
53 /// Limit price for the order. Required for Limit/StopLimit orders.
54 /// `None` for Market/Stop/TrailingStop orders (which execute at market price when triggered),
55 /// and for TrailingStopLimit orders, whose limit price follows from their stop and
56 /// `limit_offset`.
57 pub price: Option<Decimal>,
58 pub quantity: Decimal,
59 pub kind: OrderKind,
60 pub time_in_force: TimeInForce,
61 /// Target `PositionId` for this order in `OmsMode::Hedging`.
62 ///
63 /// For opening orders: the position this fill should open or add to.
64 /// For closing orders: the position this fill should reduce or close.
65 /// In `OmsMode::Netting`, leave as `None` (ignored).
66 #[serde(default)]
67 pub position_id: Option<PositionId>,
68 /// Constrain this order to only reduce existing positions, never open new ones.
69 ///
70 /// Used by exchanges that require explicit open/close intent (Alpaca, Interactive
71 /// Brokers, Schwab). Adapters derive venue-specific semantics from this flag + `side`:
72 /// - `reduce_only=false, Buy` → BuyToOpen (open long / add to long)
73 /// - `reduce_only=false, Sell` → SellToOpen (open short / write option)
74 /// - `reduce_only=true, Buy` → BuyToClose (close short)
75 /// - `reduce_only=true, Sell` → SellToClose (close long)
76 ///
77 /// Exchanges that infer intent from positions (Binance, Deribit) may map this to
78 /// their `reduceOnly` parameter or ignore it entirely.
79 #[serde(default)]
80 pub reduce_only: bool,
81
82 /// Market state observed at the instant this request was created, if any was sampled.
83 ///
84 /// This is **decision-time provenance**, not an instruction to the venue. It records what the
85 /// sender was looking at when it chose to trade, which is the one price a fill can be measured
86 /// against after the fact — implementation shortfall is the difference between this and the
87 /// price actually obtained.
88 ///
89 /// # Live venues must ignore this field
90 ///
91 /// No live exchange adapter reads it and none should: a venue prices a fill from its own book,
92 /// and an adapter that forwarded these prices would be sending the client's view of the market
93 /// back as an instruction. Every adapter in this crate leaves it untouched.
94 ///
95 /// # A simulated venue fills from it only when it has no book of its own
96 ///
97 /// [`SimulatedVenue`](crate::exchange::mock::SimulatedVenue) reads this **only** in
98 /// [`VenueRegime::RequestPriced`](crate::exchange::mock::venue::VenueRegime::RequestPriced), where it
99 /// has no market feed and this snapshot is its only price source. That is the regime
100 /// [`MockExecution`](crate::client::mock::MockExecution) and
101 /// [`MockExchange`](crate::exchange::mock::MockExchange) use: the request's snapshot is priced
102 /// through the venue's [`FillModel`](crate::fill::FillModel), and without it a market order
103 /// carries no price at all — `price` is `None` by construction for [`OrderKind::Market`] — so
104 /// the venue can only reject.
105 ///
106 /// A [`MarketDriven`](crate::exchange::mock::venue::VenueRegime::MarketDriven) venue ignores it and
107 /// prices from its own book, like a live one. This field is then decision-time provenance
108 /// alone, and the difference between it and the price obtained is implementation shortfall.
109 ///
110 /// Sampling it at creation rather than at fill time is deliberate. It is the one instant with a
111 /// well-defined position on a simulated timeline *for the sender*: everything the sender had
112 /// seen by then is in it, and nothing it had not seen can be. What makes it safe for a venue to
113 /// hold a book instead is that its driver paces the feed — routing each market event to the
114 /// venue before the client that reacts to it sees the same event, and booking each request at
115 /// the instant it arrives. A venue that sampled a stream it shares with the engine but does not
116 /// pace could fill against prices from arbitrarily far in the future, which is why the regime
117 /// is a property of how the venue is driven rather than a configuration flag.
118 ///
119 /// # `None` versus an empty snapshot
120 ///
121 /// `None` means no snapshot was taken — a live path, or a caller that constructed the request
122 /// directly. `Some` holding a [`MarketSnapshot::is_empty`] snapshot means one was taken and the
123 /// instrument had no price yet, which is what a cold start looks like. A `RequestPriced`
124 /// simulated venue distinguishes the two in its rejection, because the fixes differ.
125 ///
126 /// `#[serde(default)]` so requests serialised before this field existed still load.
127 #[serde(default)]
128 pub market: Option<MarketSnapshot>,
129}
130
131#[derive(
132 Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default, Deserialize, Serialize, Constructor,
133)]
134pub struct RequestCancel {
135 /// How the venue addresses the order to cancel, when that is known.
136 ///
137 /// Three cases, and a client must distinguish all three:
138 /// - `None` -- the order is still in flight, so the venue has acknowledged nothing and there
139 /// is no identifier to cancel by.
140 /// - `Some(VenueOrderId::Assigned(id))` -- cancel by the venue's identifier.
141 /// - `Some(VenueOrderId::ClientAssigned)` -- the venue accepted the order without assigning an
142 /// identifier; cancel by the `ClientOrderId` in the request's key.
143 ///
144 /// Collapsing the last two into `None` would leave a client unable to tell "nothing to cancel"
145 /// from "cancel by client id".
146 pub id: Option<VenueOrderId>,
147}