bybit/models/order_data.rs
1use crate::prelude::*;
2
3/// Represents order data for a trading order on Bybit's perpetual futures platform.
4///
5/// This struct encapsulates all details of an order, including its type, status, and associated financial metrics.
6/// It is used in Bybit's WebSocket and REST APIs to convey order information (https://bybit-exchange.github.io/docs/v5/websocket/private/order).
7/// In the context of perpetual futures, orders are instructions to buy or sell a contract that tracks the price of an underlying asset without an expiration date.
8/// For trading bots, this struct is critical for tracking order execution, managing risk, and implementing strategies like market making or arbitrage.
9#[derive(Serialize, Deserialize, Debug, Clone)]
10#[serde(rename_all = "camelCase")]
11pub struct OrderData {
12 /// The trading pair or contract symbol, e.g., "BTCUSDT" for Bitcoin/Tether perpetual futures.
13 ///
14 /// In Bybit, the symbol uniquely identifies the perpetual futures contract. Perpetual futures are derivatives that allow traders to speculate on asset prices with leverage, without owning the underlying asset (https://bybit-exchange.github.io/docs/v5/market/instrument).
15 /// For trading bots, this field is essential for routing orders to the correct market and ensuring strategy alignment with specific contracts.
16 pub symbol: String,
17
18 /// Unique identifier for the order, assigned by Bybit.
19 ///
20 /// This ID is used to track and manage orders via Bybit's API (https://bybit-exchange.github.io/docs/v5/order/create-order). It allows bots to query order status, cancel orders, or amend them.
21 /// In perpetual futures trading, order IDs are critical for maintaining state in high-frequency trading systems, ensuring no duplicate or lost orders.
22 pub order_id: String,
23
24 /// Indicates whether the order is a buy or sell, e.g., "Buy" or "Sell".
25 ///
26 /// The side determines the direction of the trade in the perpetual futures market. A "Buy" order increases exposure to the asset (long position), while a "Sell" order decreases it (short position).
27 /// Bots use this field to manage position direction and ensure alignment with market signals or hedging strategies (https://bybit-exchange.github.io/docs/v5/order/order-list).
28 pub side: String,
29
30 /// Specifies the type of order, e.g., "Limit", "Market".
31 ///
32 /// Bybit supports various order types for perpetual futures, such as limit orders (executed at a specified price) and market orders (executed at the best available price).
33 /// Bots rely on this field to implement strategies like limit order books for liquidity provision or market orders for immediate execution (https://bybit-exchange.github.io/docs/v5/order/create-order).
34 pub order_type: String,
35
36 /// Indicates the reason or type of order cancellation, if applicable.
37 ///
38 /// This field is relevant when an order is canceled due to conditions like insufficient margin or timeout. In perpetual futures, cancellations can occur due to rapid market movements or risk limits.
39 /// For bots, monitoring this field helps diagnose issues like order rejections and adjust strategies to avoid repeated cancellations.
40 pub cancel_type: String,
41
42 /// The price at which the order is placed (for limit orders) or executed (for market orders).
43 ///
44 /// In perpetual futures, the price is critical for calculating entry points and potential profits. Bybit represents prices in USDT or the quote currency (https://bybit-exchange.github.io/docs/v5/order/order-list).
45 /// Bots use this field to set precise entry/exit points and manage slippage in volatile markets.
46 #[serde(with = "string_to_float")]
47 pub price: f64,
48
49 /// The quantity of the contract to be traded, expressed in contracts or lots.
50 ///
51 /// For perpetual futures on Bybit, quantity represents the size of the position. Larger quantities increase exposure and risk, especially with leverage (https://bybit-exchange.github.io/docs/v5/order/create-order).
52 /// Bots use this field to scale positions based on account size, risk tolerance, andავ
53 /// The quantity of the contract to be traded, expressed in contracts or lots.
54 ///
55 /// For perpetual futures on Bybit, quantity represents the size of the position. Larger quantities increase exposure and risk, especially with leverage (https://bybit-exchange.github.io/docs/v5/order/create-order).
56 /// Bots use this field to scale positions based on account size, risk tolerance, and market conditions.
57 #[serde(with = "string_to_float")]
58 pub qty: f64,
59
60 /// Implied volatility associated with the order, if applicable.
61 ///
62 /// This field is typically used for options or volatility-based derivatives, not standard perpetual futures. It may be empty or unused in this context.
63 /// For bots, this field is generally irrelevant unless dealing with Bybit's volatility products, which are less common.
64 #[serde(deserialize_with = "empty_string_as_none")]
65 pub order_iv: Option<String>,
66
67 /// Specifies how long the order remains active, e.g., "GTC" (Good Till Cancel), "IOC" (Immediate or Cancel).
68 ///
69 /// Time in force controls order execution behavior in Bybit's perpetual futures market (https://bybit-exchange.github.io/docs/v5/order/create-order).
70 /// Bots use this field to manage order persistence, balancing execution speed with market exposure.
71 pub time_in_force: String,
72
73 /// Current status of the order, e.g., "New", "Filled", "Cancelled".
74 ///
75 /// This field tracks the lifecycle of an order on Bybit (https://bybit-exchange.github.io/docs/v5/order/order-list). In perpetual futures, understanding order status is crucial for managing open positions and avoiding unintended exposures.
76 /// Bots monitor this field to confirm executions, handle partial fills, or trigger fallback strategies.
77 /// **Order Status Monitoring**: Trading bots heavily rely on real-time order status updates to manage risk and ensure accurate position tracking. For instance, a "Filled" status confirms execution, while "Rejected" may require immediate re-evaluation of the strategy.
78 pub order_status: String,
79
80 /// A custom identifier for the order, set by the user or bot.
81 ///
82 /// This allows bots to attach metadata to orders for internal tracking, such as strategy IDs or batch identifiers. It’s particularly useful in high-frequency trading to correlate orders with specific algorithms or events (https://bybit-exchange.github.io/docs/v5/order/create-order).
83 /// **Bot Implication**: Using meaningful `order_link_id` values can streamline reconciliation and debugging, especially when handling thousands of orders daily.
84 #[serde(deserialize_with = "empty_string_as_none")]
85 pub order_link_id: Option<String>,
86
87 /// The market price of the symbol when the order was created.
88 ///
89 /// This field captures the reference price at order placement, useful for auditing and performance analysis in perpetual futures trading. It helps bots assess slippage (the difference between `last_price_on_created` and `price`) and market conditions at the time of order submission.
90 /// **Bot Implication**: Bots can use this to evaluate execution quality, especially for market orders where slippage can significantly impact profitability in volatile markets like crypto futures.
91 #[serde(with = "string_to_float")]
92 pub last_price_on_created: f64,
93
94 /// Indicates if the order reduces an existing position (true) or opens a new one (false).
95 ///
96 /// In perpetual futures, `reduce_only` orders ensure that the trade only closes or reduces a position, preventing accidental increases in exposure (https://bybit-exchange.github.io/docs/v5/order/create-order).
97 /// **Bot Implication**: Bots must set this correctly to avoid unintended leverage increases, which could lead to margin calls or liquidations in highly leveraged markets=1. **Risk Management**: Using `reduce_only` orders is critical for bots managing position sizing to prevent over-leveraging, especially in volatile markets where margin requirements can change rapidly.
98 pub reduce_only: bool,
99
100 /// The remaining quantity of the order that has not yet been filled.
101 ///
102 /// For partially filled orders, this field tracks how much of the original `qty` remains open. In perpetual futures, partial fills are common due to market liquidity constraints (https://bybit-exchange.github.io/docs/v5/order/order-list).
103 /// **Bot Implication**: Bots need to monitor `leaves_qty` to decide whether to cancel the remaining order, adjust the price, or wait for further execution, balancing execution risk with market exposure.
104 #[serde(with = "string_to_float_optional")]
105 pub leaves_qty: Option<f64>,
106
107 /// The remaining value of the order, calculated as `leaves_qty` multiplied by the order price.
108 ///
109 /// This provides the monetary value of the unfilled portion of the order, useful for assessing exposure in USDT or the quote currency.
110 /// **Bot Implication**: Bots use `leaves_value` to quantify the capital tied up in open orders, aiding in capital allocation and risk management.
111 #[serde(with = "string_to_float_optional")]
112 pub leaves_value: Option<f64>,
113
114 /// The total quantity executed so far for this order.
115 ///
116 /// This tracks the cumulative filled portion of the order, critical for monitoring progress toward full execution (https://bybit-exchange.github.io/docs/v5/order/order-list).
117 /// **Bot Implication**: Bots use `cum_exec_qty` to calculate position size, update risk models, and determine whether additional orders are needed to achieve the desired exposure.
118 #[serde(with = "string_to_float_optional")]
119 pub cum_exec_qty: Option<f64>,
120
121 /// The total monetary value of the executed portion, calculated as `cum_exec_qty` multiplied by the average execution price.
122 ///
123 /// This quantifies the capital deployed in the executed portion of the order, useful for performance tracking and cost analysis.
124 /// **Bot Implication**: Bots use `cum_exec_value` to assess trade costs, including fees, and to evaluate the profitability of partially filled orders.
125 #[serde(with = "string_to_float")]
126 pub cum_exec_value: f64,
127
128 /// The average price at which the executed portion of the order was filled.
129 ///
130 /// This is calculated as the total value of executed trades divided by `cum_exec_qty`. It provides a weighted average execution price, reflecting market conditions during filling (https://bybit-exchange.github.io/docs/v5/order/order-list).
131 /// **Bot Implication**: Bots use `avg_price` to evaluate trade execution quality, compare it to `last_price_on_created`, and adjust strategies to minimize slippage in future orders.
132 #[serde(with = "string_to_float_optional")]
133 pub avg_price: Option<f64>,
134
135 /// Identifier for a block trade, if applicable.
136 ///
137 /// Block trades are large, negotiated trades executed outside the public order book, often used by institutional traders. This field is typically empty for retail bots (https://bybit-exchange.github.io/docs/v5/trade/block-trade).
138 /// **Bot Implication**: For most retail bots, this field is unused, but large-scale bots may use it to track high-value trades separately for reporting or compliance.
139 #[serde(deserialize_with = "empty_string_as_none")]
140 pub block_trade_id: Option<String>,
141
142 /// Index indicating the position direction, e.g., 0 for one-way mode, 1 for buy-side hedge, 2 for sell-side hedge.
143 ///
144 /// Bybit’s unified margin account supports one-way or hedge modes for perpetual futures positions (https://bybit-exchange.github.io/docs/v5/account/position).
145 /// **Bot Implication**: Bots must align `position_idx` with the account’s position mode to avoid position mismatches, which could lead to unintended liquidations.
146 #[serde(rename = "positionIdx")]
147 pub position_idx: u8,
148
149 /// The cumulative trading fees incurred for this order.
150 ///
151 /// Fees in perpetual futures include maker/taker fees, which impact profitability. Bybit’s fee structure varies by VIP level and order type (https://bybit-exchange.github.io/docs/v5/account/fee).
152 /// **Bot Implication**: Bots must track `cum_exec_fee` to optimize order types (e.g., maker vs. taker) and account for fees in profitability calculations, as high-frequency trading can accumulate significant costs.
153 #[serde(with = "string_to_float_optional")]
154 pub cum_exec_fee: Option<f64>,
155
156 /// Timestamp when the order was created, in milliseconds since Unix epoch.
157 ///
158 /// This records the exact time of order submission, critical for auditing and performance analysis (https://bybit-exchange.github.io/docs/v5/order/order-list).
159 /// **Bot Implication**: Bots use `created_time` to correlate orders with market events, calculate latency, and ensure compliance with exchange timestamps.
160 #[serde(with = "string_to_u64")]
161 pub created_time: u64,
162
163 /// Timestamp of the last update to the order, in milliseconds since Unix epoch.
164 ///
165 /// This tracks the most recent change to the order’s status, such as partial fills or cancellations (https://bybit-exchange.github.io/docs/v5/order/order-list).
166 /// **Bot Implication**: Bots use `updated_time` to detect delays in execution or status changes, enabling timely adjustments to strategies or risk controls.
167 #[serde(with = "string_to_u64")]
168 pub updated_time: u64,
169
170 /// Reason for order rejection, if applicable, e.g., "Insufficient margin".
171 ///
172 /// This field explains why an order failed to execute, helping diagnose issues like funding shortages or invalid parameters (https://bybit-exchange.github.io/docs/v5/order/order-list).
173 /// **Bot Implication**: Bots must monitor `reject_reason` to handle errors programmatically, such as topping up margin or adjusting order parameters to prevent repeated failures.
174 pub reject_reason: String,
175
176 /// Type of stop order, e.g., "Stop", "TrailingStop", if applicable.
177 ///
178 /// Stop orders in perpetual futures are conditional orders triggered by price movements, used for risk management (https://bybit-exchange.github.io/docs/v5/order/stop-order).
179 /// **Bot Implication**: Bots use `stop_order_type` to implement automated stop-loss or trailing stops, critical for limiting losses in leveraged positions.
180 #[serde(rename = "stopOrderType", deserialize_with = "empty_string_as_none")]
181 pub stop_order_type: Option<String>,
182
183 /// Take-profit/stop-loss mode, e.g., "Full", "Partial".
184 ///
185 /// This defines how take-profit and stop-loss orders are applied in Bybit’s unified margin account, either to the full position or a portion (https://bybit-exchange.github.io/docs/v5/order/tpsl-mode).
186 /// **Bot Implication**: Bots must configure `tpsl_mode` to align with risk management strategies, ensuring partial or full position exits as intended.
187 #[serde(rename = "tpslMode", deserialize_with = "empty_string_as_none")]
188 pub tpsl_mode: Option<String>,
189
190 /// Price level that triggers a stop order.
191 ///
192 /// In perpetual futures, the trigger price determines when a stop-loss or other conditional order activates (https://bybit-exchange.github.io/docs/v5/order/stop-order).
193 /// **Bot Implication**: Bots set `trigger_price` to automate risk controls, ensuring timely exits from losing positions to prevent margin calls or liquidations.
194 #[serde(with = "string_to_float_optional")]
195 pub trigger_price: Option<f64>,
196
197 /// Price level at which a take-profit order is triggered.
198 ///
199 /// Take-profit orders lock in gains by closing a position when the market reaches a favorable price (https://bybit-exchange.github.io/docs/v5/order/tpsl-order).
200 /// **Bot Implication**: Bots use `take_profit` to secure profits automatically, balancing the trade-off between capturing gains and allowing room for further upside.
201 #[serde(with = "string_to_float_optional")]
202 pub take_profit: Option<f64>,
203
204 /// Price level at which a stop-loss order is triggered.
205 ///
206 /// Stop-loss orders limit losses by closing a position when the market moves against it (https://bybit-exchange.github.io/docs/v5/order/tpsl-order).
207 /// **Bot Implication**: Bots set `stop_loss` to cap downside risk, a critical feature for leveraged perpetual futures where losses can exceed initial margin.
208 #[serde(with = "string_to_float_optional")]
209 pub stop_loss: Option<f64>,
210
211 /// Specifies the price type that triggers the take-profit order, e.g., "LastPrice", "IndexPrice".
212 ///
213 /// Bybit allows different price feeds for triggering orders, affecting how take-profit is calculated (https://bybit-exchange.github.io/docs/v5/order/tpsl-order).
214 /// **Bot Implication**: Bots must select the appropriate `tp_trigger_by` to align with strategy logic, as different price types can lead to varying trigger points.
215 #[serde(rename = "tpTriggerBy", deserialize_with = "empty_string_as_none")]
216 pub tp_trigger_by: Option<String>,
217
218 /// Specifies the price type that triggers the stop-loss order, e.g., "LastPrice", "IndexPrice".
219 ///
220 /// Similar to `tp_trigger_by`, this determines the reference price for stop-loss activation (https://bybit-exchange.github.io/docs/v5/order/tpsl-order).
221 /// **Bot Implication**: Bots need to choose `sl_trigger_by` carefully, as price feed discrepancies can cause premature or delayed stop-loss triggers.
222 #[serde(rename = "slTriggerBy", deserialize_with = "empty_string_as_none")]
223 pub sl_trigger_by: Option<String>,
224
225 /// Limit price for the take-profit order, if applicable.
226 ///
227 /// This specifies the exact price at which the take-profit order executes once triggered, allowing precise profit capture (https://bybit-exchange.github.io/docs/v5/order/tpsl-order).
228 /// **Bot Implication**: Bots use `tp_limit_price` to minimize slippage on take-profit execution, ensuring profits are locked in at the desired level.
229 #[serde(rename = "tpLimitPrice", with = "string_to_float_optional")]
230 pub tp_limit_price: Option<f64>,
231
232 /// Limit price for the stop-loss order, if applicable.
233 ///
234 /// This sets the execution price for the stop-loss order once triggered, controlling the exit price in adverse market moves (https://bybit-exchange.github.io/docs/v5/order/tpsl-order).
235 /// **Bot Implication**: Bots set `sl_limit_price` to balance loss minimization with the risk of slippage, especially in fast-moving markets.
236 #[serde(rename = "slLimitPrice", with = "string_to_float_optional")]
237 pub sl_limit_price: Option<f64>,
238
239 /// Direction of the price movement that triggers the order, e.g., 1 for rising price, 2 for falling price.
240 ///
241 /// This defines whether the stop or take-profit order activates on an upward or downward price move (https://bybit-exchange.github.io/docs/v5/order/stop-order).
242 /// **Bot Implication**: Bots must set `trigger_direction` correctly to align with the intended risk or profit-taking logic, as incorrect settings can lead to unintended executions.
243 pub trigger_direction: u8,
244
245 /// The price type that triggers the conditional order, e.g., "LastPrice", "MarkPrice".
246 ///
247 /// Similar to `tp_trigger_by` and `sl_trigger_by`, this specifies the reference price for conditional orders (https://bybit-exchange.github.io/docs/v5/order/stop-order).
248 /// **Bot Implication**: Bots need to ensure `trigger_by` matches the strategy’s price feed to avoid discrepancies in trigger timing.
249 #[serde(deserialize_with = "empty_string_as_none")]
250 pub trigger_by: Option<String>,
251
252 /// Indicates if the order closes the position when triggered.
253 ///
254 /// When `true`, the order ensures the position is fully closed upon trigger, used in stop-loss or take-profit scenarios (https://bybit-exchange.github.io/docs/v5/order/tpsl-order).
255 /// **Bot Implication**: Bots use `close_on_trigger` to enforce complete position exits, critical for risk management in leveraged perpetual futures.
256 pub close_on_trigger: bool,
257
258 /// The product category, e.g., "linear", "inverse".
259 ///
260 /// Bybit offers linear (USDT-margined) and inverse (coin-margined) perpetual futures, each with different margin and settlement mechanics (https://bybit-exchange.github.io/docs/v5/market/instrument).
261 /// **Bot Implication**: Bots must align `category` with the account’s margin type to ensure correct position and margin calculations.
262 pub category: String,
263
264 /// Indicates how the order was placed, e.g., "Normal", "Adl" (Auto-Deleveraging).
265 ///
266 /// This field distinguishes standard orders from those triggered by Bybit’s risk management processes, like ADL (https://bybit-exchange.github.io/docs/v5/account/position#auto-deleveraging-adl).
267 /// **Bot Implication**: Bots should monitor `place_type` to identify non-standard orders, which may indicate risk events like forced liquidations.
268 pub place_type: String,
269
270 /// Self-Match Prevention (SMP) type, if applicable.
271 ///
272 /// SMP prevents orders from the same account matching each other, reducing wash trading risks (https://bybit-exchange.github.io/docs/v5/order/smp).
273 /// **Bot Implication**: Bots in multi-strategy setups should track `smp_type` to ensure compliance with Bybit’s trading rules and avoid penalties.
274 pub smp_type: String,
275
276 /// Group ID for SMP, if applicable.
277 ///
278 /// This identifies the SMP group to which the order belongs, used to enforce self-match prevention (https://bybit-exchange.github.io/docs/v5/order/smp).
279 /// **Bot Implication**: Bots managing multiple sub-accounts or strategies use `smp_group` to coordinate orders and prevent internal matching.
280 pub smp_group: u8,
281
282 /// Order ID of the matching order in an SMP scenario, if applicable.
283 ///
284 /// This links the order to its counterpart in an SMP event, aiding in audit trails (https://bybit-exchange.github.io/docs/v5/order/smp).
285 /// **Bot Implication**: Bots use `smp_order_id` for reconciliation and compliance reporting, ensuring transparency in SMP events.
286 #[serde(deserialize_with = "empty_string_as_none")]
287 pub smp_order_id: Option<String>,
288
289 /// The currency used for fees, e.g., "USDT".
290 ///
291 /// This specifies the currency in which trading fees are charged, impacting cost calculations (https://bybit-exchange.github.io/docs/v5/account/fee).
292 /// **Bot Implication**: Bots must account for `fee_currency` in profitability models, as fees in volatile currencies like USDT can affect net returns.
293 #[serde(deserialize_with = "empty_string_as_none")]
294 pub fee_currency: Option<String>,
295}