ig_client/application/models/
order.rs

1/******************************************************************************
2   Author: Joaquín Béjar García
3   Email: jb@taunais.com
4   Date: 13/5/25
5******************************************************************************/
6use crate::impl_json_display;
7use serde::{Deserialize, Deserializer, Serialize};
8
9const DEFAULT_ORDER_SELL_SIZE: f64 = 0.0;
10const DEFAULT_ORDER_BUY_SIZE: f64 = 10000.0;
11
12/// Order direction (buy or sell)
13#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
14#[serde(rename_all = "UPPERCASE")]
15pub enum Direction {
16    /// Buy direction (long position)
17    #[default]
18    Buy,
19    /// Sell direction (short position)
20    Sell,
21}
22
23impl_json_display!(Direction);
24
25/// Order type
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
27#[serde(rename_all = "UPPERCASE")]
28pub enum OrderType {
29    /// Limit order - executed when price reaches specified level
30    #[default]
31    Limit,
32    /// Market order - executed immediately at current market price
33    Market,
34    /// Quote order - executed at quoted price
35    Quote,
36    /// Stop order - becomes market order when price reaches specified level
37    Stop,
38    /// Stop limit order - becomes limit order when price reaches specified level
39    StopLimit,
40}
41
42/// Represents the status of an order or transaction in the system.
43///
44/// This enum covers various states an order can be in throughout its lifecycle,
45/// from creation to completion or cancellation.
46#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
47#[serde(rename_all = "UPPERCASE")]
48pub enum Status {
49    /// Order has been amended or modified after initial creation
50    Amended,
51    /// Order has been deleted from the system
52    Deleted,
53    /// Order has been completely closed with all positions resolved
54    #[serde(rename = "FULLY_CLOSED")]
55    FullyClosed,
56    /// Order has been opened and is active in the market
57    Opened,
58    /// Order has been partially closed with some positions still open
59    #[serde(rename = "PARTIALLY_CLOSED")]
60    PartiallyClosed,
61    /// Order has been closed but may differ from FullyClosed in context
62    Closed,
63    /// Default state - order is open and active in the market
64    #[default]
65    Open,
66    /// Order has been updated with new parameters
67    Updated,
68    /// Order has been accepted by the system or exchange
69    Accepted,
70    /// Order has been rejected by the system or exchange
71    Rejected,
72    /// Order is currently working (waiting to be filled)
73    Working,
74    /// Order has been filled (executed)
75    Filled,
76    /// Order has been cancelled
77    Cancelled,
78    /// Order has expired (time in force elapsed)
79    Expired,
80}
81
82/// Order duration (time in force)
83#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
84pub enum TimeInForce {
85    /// Order remains valid until cancelled by the client
86    #[serde(rename = "GOOD_TILL_CANCELLED")]
87    #[default]
88    GoodTillCancelled,
89    /// Order remains valid until a specified date
90    #[serde(rename = "GOOD_TILL_DATE")]
91    GoodTillDate,
92    /// Order is executed immediately (partially or completely) or cancelled
93    #[serde(rename = "IMMEDIATE_OR_CANCEL")]
94    ImmediateOrCancel,
95    /// Order must be filled completely immediately or cancelled
96    #[serde(rename = "FILL_OR_KILL")]
97    FillOrKill,
98}
99
100/// Model for creating a new order
101#[derive(Debug, Clone, Serialize)]
102pub struct CreateOrderRequest {
103    /// Instrument EPIC identifier
104    pub epic: String,
105    /// Order direction (buy or sell)
106    pub direction: Direction,
107    /// Order size/quantity
108    pub size: f64,
109    /// Type of order (market, limit, etc.)
110    #[serde(rename = "orderType")]
111    pub order_type: OrderType,
112    /// Order duration (how long the order remains valid)
113    #[serde(rename = "timeInForce")]
114    pub time_in_force: TimeInForce,
115    /// Price level for limit orders
116    #[serde(rename = "level", skip_serializing_if = "Option::is_none")]
117    pub level: Option<f64>,
118    /// Whether to use a guaranteed stop
119    #[serde(rename = "guaranteedStop", skip_serializing_if = "Option::is_none")]
120    pub guaranteed_stop: Option<bool>,
121    /// Price level for stop loss
122    #[serde(rename = "stopLevel", skip_serializing_if = "Option::is_none")]
123    pub stop_level: Option<f64>,
124    /// Distance for stop loss
125    #[serde(rename = "stopDistance", skip_serializing_if = "Option::is_none")]
126    pub stop_distance: Option<f64>,
127    /// Price level for take profit
128    #[serde(rename = "limitLevel", skip_serializing_if = "Option::is_none")]
129    pub limit_level: Option<f64>,
130    /// Distance for take profit
131    #[serde(rename = "limitDistance", skip_serializing_if = "Option::is_none")]
132    pub limit_distance: Option<f64>,
133    /// Expiry date for the order
134    #[serde(rename = "expiry", skip_serializing_if = "Option::is_none")]
135    pub expiry: Option<String>,
136    /// Client-generated reference for the deal
137    #[serde(rename = "dealReference", skip_serializing_if = "Option::is_none")]
138    pub deal_reference: Option<String>,
139    /// Whether to force open a new position
140    #[serde(rename = "forceOpen", skip_serializing_if = "Option::is_none")]
141    pub force_open: Option<bool>,
142    /// Currency code for the order (e.g., "USD", "EUR")
143    #[serde(rename = "currencyCode", skip_serializing_if = "Option::is_none")]
144    pub currency_code: Option<String>,
145}
146
147impl CreateOrderRequest {
148    /// Creates a new market order
149    pub fn market(epic: String, direction: Direction, size: f64) -> Self {
150        Self {
151            epic,
152            direction,
153            size,
154            order_type: OrderType::Market,
155            time_in_force: TimeInForce::FillOrKill,
156            level: None,
157            guaranteed_stop: None,
158            stop_level: None,
159            stop_distance: None,
160            limit_level: None,
161            limit_distance: None,
162            expiry: None,
163            deal_reference: None,
164            force_open: Some(true),
165            currency_code: None,
166        }
167    }
168
169    /// Creates a new limit order
170    pub fn limit(epic: String, direction: Direction, size: f64, level: f64) -> Self {
171        Self {
172            epic,
173            direction,
174            size,
175            order_type: OrderType::Limit,
176            time_in_force: TimeInForce::GoodTillCancelled,
177            level: Some(level),
178            guaranteed_stop: None,
179            stop_level: None,
180            stop_distance: None,
181            limit_level: None,
182            limit_distance: None,
183            expiry: None,
184            deal_reference: None,
185            force_open: Some(true),
186            currency_code: None,
187        }
188    }
189
190    /// Creates a new instance of a market sell option with predefined parameters.
191    ///
192    /// This function sets up a sell option to the market for a given asset (`epic`)
193    /// with the specified size. It configures the order with default values
194    /// for attributes such as direction, order type, and time-in-force.
195    ///
196    /// # Parameters
197    /// - `epic`: A `String` that represents the epic (unique identifier or code) of the instrument
198    ///   being traded.
199    /// - `size`: A `f64` value representing the size or quantity of the order.
200    ///
201    /// # Returns
202    /// An instance of `Self` (the type implementing this function), containing the specified
203    /// `epic` and `size`, along with default values for other parameters:
204    ///
205    /// - `direction`: Set to `Direction::Sell`.
206    /// - `order_type`: Set to `OrderType::Limit`.
207    /// - `time_in_force`: Set to `TimeInForce::FillOrKill`.
208    /// - `level`: Set to `Some(0.1)`.
209    /// - `guaranteed_stop`: Set to `None`.
210    /// - `stop_level`: Set to `None`.
211    /// - `stop_distance`: Set to `None`.
212    /// - `limit_level`: Set to `None`.
213    /// - `limit_distance`: Set to `None`.
214    /// - `expiry`: Set to `None`.
215    /// - `deal_reference`: Set to `None`.
216    /// - `force_open`: Set to `Some(true)`.
217    /// - `currency_code`: Set to `None`.
218    ///
219    /// Note that this function allows for minimal input (the instrument and size),
220    /// while other fields are provided default values. If further customization is required,
221    /// you can modify the returned instance as needed.
222    pub fn sell_option_to_market(
223        epic: String,
224        size: f64,
225        expiry: Option<String>,
226        deal_reference: Option<String>,
227        currency_code: Option<String>,
228    ) -> Self {
229        Self {
230            epic,
231            direction: Direction::Sell,
232            size,
233            order_type: OrderType::Limit,
234            time_in_force: TimeInForce::FillOrKill,
235            level: Some(DEFAULT_ORDER_SELL_SIZE),
236            guaranteed_stop: Some(false),
237            stop_level: None,
238            stop_distance: None,
239            limit_level: None,
240            limit_distance: None,
241            expiry,
242            deal_reference,
243            force_open: Some(true),
244            currency_code,
245        }
246    }
247
248    /// Creates a new instance of an order to buy an option in the market with specified parameters.
249    ///
250    /// This method initializes an order with the following default values:
251    /// - `direction` is set to `Buy`.
252    /// - `order_type` is set to `Limit`.
253    /// - `time_in_force` is set to `FillOrKill`.
254    /// - `level` is set to `Some(10000.0)`.
255    /// - `force_open` is set to `Some(true)`.
256    ///   Other optional parameters, such as stop levels, distances, expiry, and currency code, are left as `None`.
257    ///
258    /// # Parameters
259    /// - `epic` (`String`): The identifier for the market or instrument to trade.
260    /// - `size` (`f64`): The size or quantity of the order to be executed.
261    ///
262    /// # Returns
263    /// A new instance of `Self` that represents the configured buy option for the given market.
264    ///
265    /// # Note
266    /// Ensure the `epic` and `size` values provided are valid and match required market conditions.
267    pub fn buy_option_to_market(
268        epic: String,
269        size: f64,
270        expiry: Option<String>,
271        deal_reference: Option<String>,
272        currency_code: Option<String>,
273    ) -> Self {
274        Self {
275            epic,
276            direction: Direction::Buy,
277            size,
278            order_type: OrderType::Limit,
279            time_in_force: TimeInForce::FillOrKill,
280            level: Some(DEFAULT_ORDER_BUY_SIZE),
281            guaranteed_stop: Some(false),
282            stop_level: None,
283            stop_distance: None,
284            limit_level: None,
285            limit_distance: None,
286            expiry,
287            deal_reference,
288            force_open: Some(true),
289            currency_code,
290        }
291    }
292
293    /// Adds a stop loss to the order
294    pub fn with_stop_loss(mut self, stop_level: f64) -> Self {
295        self.stop_level = Some(stop_level);
296        self
297    }
298
299    /// Adds a take profit to the order
300    pub fn with_take_profit(mut self, limit_level: f64) -> Self {
301        self.limit_level = Some(limit_level);
302        self
303    }
304
305    /// Adds a reference to the order
306    pub fn with_reference(mut self, reference: String) -> Self {
307        self.deal_reference = Some(reference);
308        self
309    }
310}
311
312/// Response to order creation
313#[derive(Debug, Clone, Deserialize)]
314pub struct CreateOrderResponse {
315    /// Client-generated reference for the deal
316    #[serde(rename = "dealReference")]
317    pub deal_reference: String,
318}
319
320/// Helper function to deserialize a nullable status field
321/// When the status is null in the JSON, we default to Rejected status
322fn deserialize_nullable_status<'de, D>(deserializer: D) -> Result<Status, D::Error>
323where
324    D: Deserializer<'de>,
325{
326    let opt = Option::deserialize(deserializer)?;
327    Ok(opt.unwrap_or(Status::Rejected))
328}
329
330/// Details of a confirmed order
331#[derive(Debug, Clone, Deserialize)]
332pub struct OrderConfirmation {
333    /// Date and time of the confirmation
334    pub date: String,
335    /// Status of the order (accepted, rejected, etc.)
336    /// This can be null in some responses (e.g., when market is closed)
337    #[serde(deserialize_with = "deserialize_nullable_status")]
338    pub status: Status,
339    /// Reason for rejection if applicable
340    pub reason: Option<String>,
341    /// Unique identifier for the deal
342    #[serde(rename = "dealId")]
343    pub deal_id: Option<String>,
344    /// Client-generated reference for the deal
345    #[serde(rename = "dealReference")]
346    pub deal_reference: String,
347    /// Status of the deal
348    #[serde(rename = "dealStatus")]
349    pub deal_status: Option<String>,
350    /// Instrument EPIC identifier
351    pub epic: Option<String>,
352    /// Expiry date for the order
353    #[serde(rename = "expiry")]
354    pub expiry: Option<String>,
355    /// Whether a guaranteed stop was used
356    #[serde(rename = "guaranteedStop")]
357    pub guaranteed_stop: Option<bool>,
358    /// Price level of the order
359    #[serde(rename = "level")]
360    pub level: Option<f64>,
361    /// Distance for take profit
362    #[serde(rename = "limitDistance")]
363    pub limit_distance: Option<f64>,
364    /// Price level for take profit
365    #[serde(rename = "limitLevel")]
366    pub limit_level: Option<f64>,
367    /// Size/quantity of the order
368    pub size: Option<f64>,
369    /// Distance for stop loss
370    #[serde(rename = "stopDistance")]
371    pub stop_distance: Option<f64>,
372    /// Price level for stop loss
373    #[serde(rename = "stopLevel")]
374    pub stop_level: Option<f64>,
375    /// Whether a trailing stop was used
376    #[serde(rename = "trailingStop")]
377    pub trailing_stop: Option<bool>,
378    /// Direction of the order (buy or sell)
379    pub direction: Option<Direction>,
380}
381
382/// Model for updating an existing position
383#[derive(Debug, Clone, Serialize)]
384pub struct UpdatePositionRequest {
385    /// New price level for stop loss
386    #[serde(rename = "stopLevel", skip_serializing_if = "Option::is_none")]
387    pub stop_level: Option<f64>,
388    /// New price level for take profit
389    #[serde(rename = "limitLevel", skip_serializing_if = "Option::is_none")]
390    pub limit_level: Option<f64>,
391    /// Whether to enable trailing stop
392    #[serde(rename = "trailingStop", skip_serializing_if = "Option::is_none")]
393    pub trailing_stop: Option<bool>,
394    /// Distance for trailing stop
395    #[serde(
396        rename = "trailingStopDistance",
397        skip_serializing_if = "Option::is_none"
398    )]
399    pub trailing_stop_distance: Option<f64>,
400}
401
402/// Model for closing an existing position
403#[derive(Debug, Clone, Serialize)]
404pub struct ClosePositionRequest {
405    /// Unique identifier for the position to close
406    #[serde(rename = "dealId")]
407    pub deal_id: Option<String>,
408    /// Direction of the closing order (opposite to the position)
409    pub direction: Direction,
410    /// Size/quantity to close
411    pub size: f64,
412    /// Type of order to use for closing
413    #[serde(rename = "orderType")]
414    pub order_type: OrderType,
415    /// Order duration for the closing order
416    #[serde(rename = "timeInForce")]
417    pub time_in_force: TimeInForce,
418    /// Price level for limit close orders
419    #[serde(rename = "level", skip_serializing_if = "Option::is_none")]
420    pub level: Option<f64>,
421    /// Expiry date for the order
422    #[serde(rename = "expiry")]
423    pub expiry: Option<String>,
424    /// Instrument EPIC identifier
425    pub epic: Option<String>,
426
427    /// Quote identifier for the order, used for certain order types that require a specific quote
428    #[serde(rename = "quoteId")]
429    pub quote_id: Option<String>,
430}
431
432impl ClosePositionRequest {
433    /// Creates a request to close a position at market price
434    pub fn market(deal_id: String, direction: Direction, size: f64) -> Self {
435        Self {
436            deal_id: Some(deal_id),
437            direction,
438            size,
439            order_type: OrderType::Market,
440            time_in_force: TimeInForce::FillOrKill,
441            level: None,
442            expiry: None,
443            epic: None,
444            quote_id: None,
445        }
446    }
447
448    /// Creates a request to close a position at a specific price level
449    ///
450    /// This is useful for instruments that don't support market orders
451    pub fn limit(deal_id: String, direction: Direction, size: f64, level: f64) -> Self {
452        Self {
453            deal_id: Some(deal_id),
454            direction,
455            size,
456            order_type: OrderType::Limit,
457            time_in_force: TimeInForce::FillOrKill,
458            level: Some(level),
459            expiry: None,
460            epic: None,
461            quote_id: None,
462        }
463    }
464
465    /// Creates a request to close an option position by deal ID using a limit order with predefined price levels
466    ///
467    /// This is specifically designed for options trading where market orders are not supported
468    /// and a limit order with a predefined price level is required based on the direction.
469    ///
470    /// # Arguments
471    /// * `deal_id` - The ID of the deal to close
472    /// * `direction` - The direction of the closing order (opposite of the position direction)
473    /// * `size` - The size of the position to close
474    pub fn close_option_to_market_by_id(deal_id: String, direction: Direction, size: f64) -> Self {
475        let level = match direction {
476            Direction::Buy => Some(DEFAULT_ORDER_BUY_SIZE),
477            Direction::Sell => Some(DEFAULT_ORDER_SELL_SIZE),
478        };
479        Self {
480            deal_id: Some(deal_id),
481            direction,
482            size,
483            order_type: OrderType::Limit,
484            time_in_force: TimeInForce::FillOrKill,
485            level,
486            expiry: None,
487            epic: None,
488            quote_id: None,
489        }
490    }
491
492    /// Creates a request to close an option position by epic identifier using a limit order with predefined price levels
493    ///
494    /// This is specifically designed for options trading where market orders are not supported
495    /// and a limit order with a predefined price level is required based on the direction.
496    /// This method is used when the deal ID is not available but the epic and expiry are known.
497    ///
498    /// # Arguments
499    /// * `epic` - The epic identifier of the instrument
500    /// * `expiry` - The expiry date of the option
501    /// * `direction` - The direction of the closing order (opposite of the position direction)
502    /// * `size` - The size of the position to close
503    pub fn close_option_to_market_by_epic(
504        epic: String,
505        expiry: String,
506        direction: Direction,
507        size: f64,
508    ) -> Self {
509        let level = match direction {
510            Direction::Buy => Some(DEFAULT_ORDER_BUY_SIZE),
511            Direction::Sell => Some(DEFAULT_ORDER_SELL_SIZE),
512        };
513        Self {
514            deal_id: None,
515            direction,
516            size,
517            order_type: OrderType::Limit,
518            time_in_force: TimeInForce::FillOrKill,
519            level,
520            expiry: Some(expiry),
521            epic: Some(epic),
522            quote_id: None,
523        }
524    }
525}
526
527/// Response to closing a position
528#[derive(Debug, Clone, Deserialize)]
529pub struct ClosePositionResponse {
530    /// Client-generated reference for the closing deal
531    #[serde(rename = "dealReference")]
532    pub deal_reference: String,
533}
534
535/// Response to updating a position
536#[derive(Debug, Clone, Deserialize)]
537pub struct UpdatePositionResponse {
538    /// Client-generated reference for the update deal
539    #[serde(rename = "dealReference")]
540    pub deal_reference: String,
541}
542
543/// Model for creating a new working order
544#[derive(Debug, Clone, Serialize)]
545pub struct CreateWorkingOrderRequest {
546    /// Instrument EPIC identifier
547    pub epic: String,
548    /// Order direction (buy or sell)
549    pub direction: Direction,
550    /// Order size/quantity
551    pub size: f64,
552    /// Price level for the order
553    pub level: f64,
554    /// Type of working order (LIMIT or STOP)
555    #[serde(rename = "type")]
556    pub order_type: OrderType,
557    /// Order duration (how long the order remains valid)
558    #[serde(rename = "timeInForce")]
559    pub time_in_force: TimeInForce,
560    /// Whether to use a guaranteed stop
561    #[serde(rename = "guaranteedStop", skip_serializing_if = "Option::is_none")]
562    pub guaranteed_stop: Option<bool>,
563    /// Price level for stop loss
564    #[serde(rename = "stopLevel", skip_serializing_if = "Option::is_none")]
565    pub stop_level: Option<f64>,
566    /// Distance for stop loss
567    #[serde(rename = "stopDistance", skip_serializing_if = "Option::is_none")]
568    pub stop_distance: Option<f64>,
569    /// Price level for take profit
570    #[serde(rename = "limitLevel", skip_serializing_if = "Option::is_none")]
571    pub limit_level: Option<f64>,
572    /// Distance for take profit
573    #[serde(rename = "limitDistance", skip_serializing_if = "Option::is_none")]
574    pub limit_distance: Option<f64>,
575    /// Expiry date for GTD orders
576    #[serde(rename = "goodTillDate", skip_serializing_if = "Option::is_none")]
577    pub good_till_date: Option<String>,
578    /// Client-generated reference for the deal
579    #[serde(rename = "dealReference", skip_serializing_if = "Option::is_none")]
580    pub deal_reference: Option<String>,
581    /// Currency code for the order (e.g., "USD", "EUR")
582    #[serde(rename = "currencyCode", skip_serializing_if = "Option::is_none")]
583    pub currency_code: Option<String>,
584}
585
586impl CreateWorkingOrderRequest {
587    /// Creates a new limit working order
588    pub fn limit(epic: String, direction: Direction, size: f64, level: f64) -> Self {
589        Self {
590            epic,
591            direction,
592            size,
593            level,
594            order_type: OrderType::Limit,
595            time_in_force: TimeInForce::GoodTillCancelled,
596            guaranteed_stop: None,
597            stop_level: None,
598            stop_distance: None,
599            limit_level: None,
600            limit_distance: None,
601            good_till_date: None,
602            deal_reference: None,
603            currency_code: None,
604        }
605    }
606
607    /// Creates a new stop working order
608    pub fn stop(epic: String, direction: Direction, size: f64, level: f64) -> Self {
609        Self {
610            epic,
611            direction,
612            size,
613            level,
614            order_type: OrderType::Stop,
615            time_in_force: TimeInForce::GoodTillCancelled,
616            guaranteed_stop: None,
617            stop_level: None,
618            stop_distance: None,
619            limit_level: None,
620            limit_distance: None,
621            good_till_date: None,
622            deal_reference: None,
623            currency_code: None,
624        }
625    }
626
627    /// Adds a stop loss to the working order
628    pub fn with_stop_loss(mut self, stop_level: f64) -> Self {
629        self.stop_level = Some(stop_level);
630        self
631    }
632
633    /// Adds a take profit to the working order
634    pub fn with_take_profit(mut self, limit_level: f64) -> Self {
635        self.limit_level = Some(limit_level);
636        self
637    }
638
639    /// Adds a reference to the working order
640    pub fn with_reference(mut self, reference: String) -> Self {
641        self.deal_reference = Some(reference);
642        self
643    }
644
645    /// Sets the order to expire at a specific date
646    pub fn expires_at(mut self, date: String) -> Self {
647        self.time_in_force = TimeInForce::GoodTillDate;
648        self.good_till_date = Some(date);
649        self
650    }
651}
652
653/// Response to working order creation
654#[derive(Debug, Clone, Deserialize)]
655pub struct CreateWorkingOrderResponse {
656    /// Client-generated reference for the deal
657    #[serde(rename = "dealReference")]
658    pub deal_reference: String,
659}