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    #[allow(clippy::ptr_arg)]
223    pub fn sell_option_to_market(
224        epic: &String,
225        size: &f64,
226        expiry: &Option<String>,
227        deal_reference: &Option<String>,
228        currency_code: &Option<String>,
229    ) -> Self {
230        Self {
231            epic: epic.clone(),
232            direction: Direction::Sell,
233            size: *size,
234            order_type: OrderType::Limit,
235            time_in_force: TimeInForce::FillOrKill,
236            level: Some(DEFAULT_ORDER_SELL_SIZE),
237            guaranteed_stop: Some(false),
238            stop_level: None,
239            stop_distance: None,
240            limit_level: None,
241            limit_distance: None,
242            expiry: expiry.clone(),
243            deal_reference: deal_reference.clone(),
244            force_open: Some(true),
245            currency_code: currency_code.clone(),
246        }
247    }
248
249    /// Creates a new instance of an order to buy an option in the market with specified parameters.
250    ///
251    /// This method initializes an order with the following default values:
252    /// - `direction` is set to `Buy`.
253    /// - `order_type` is set to `Limit`.
254    /// - `time_in_force` is set to `FillOrKill`.
255    /// - `level` is set to `Some(10000.0)`.
256    /// - `force_open` is set to `Some(true)`.
257    ///   Other optional parameters, such as stop levels, distances, expiry, and currency code, are left as `None`.
258    ///
259    /// # Parameters
260    /// - `epic` (`String`): The identifier for the market or instrument to trade.
261    /// - `size` (`f64`): The size or quantity of the order to be executed.
262    ///
263    /// # Returns
264    /// A new instance of `Self` that represents the configured buy option for the given market.
265    ///
266    /// # Note
267    /// Ensure the `epic` and `size` values provided are valid and match required market conditions.
268    #[allow(clippy::ptr_arg)]
269    pub fn buy_option_to_market(
270        epic: &String,
271        size: &f64,
272        expiry: &Option<String>,
273        deal_reference: &Option<String>,
274        currency_code: &Option<String>,
275    ) -> Self {
276        Self {
277            epic: epic.clone(),
278            direction: Direction::Buy,
279            size: *size,
280            order_type: OrderType::Limit,
281            time_in_force: TimeInForce::FillOrKill,
282            level: Some(DEFAULT_ORDER_BUY_SIZE),
283            guaranteed_stop: Some(false),
284            stop_level: None,
285            stop_distance: None,
286            limit_level: None,
287            limit_distance: None,
288            expiry: expiry.clone(),
289            deal_reference: deal_reference.clone(),
290            force_open: Some(true),
291            currency_code: currency_code.clone(),
292        }
293    }
294
295    /// Adds a stop loss to the order
296    pub fn with_stop_loss(mut self, stop_level: f64) -> Self {
297        self.stop_level = Some(stop_level);
298        self
299    }
300
301    /// Adds a take profit to the order
302    pub fn with_take_profit(mut self, limit_level: f64) -> Self {
303        self.limit_level = Some(limit_level);
304        self
305    }
306
307    /// Adds a reference to the order
308    pub fn with_reference(mut self, reference: String) -> Self {
309        self.deal_reference = Some(reference);
310        self
311    }
312}
313
314/// Response to order creation
315#[derive(Debug, Clone, Deserialize)]
316pub struct CreateOrderResponse {
317    /// Client-generated reference for the deal
318    #[serde(rename = "dealReference")]
319    pub deal_reference: String,
320}
321
322/// Helper function to deserialize a nullable status field
323/// When the status is null in the JSON, we default to Rejected status
324fn deserialize_nullable_status<'de, D>(deserializer: D) -> Result<Status, D::Error>
325where
326    D: Deserializer<'de>,
327{
328    let opt = Option::deserialize(deserializer)?;
329    Ok(opt.unwrap_or(Status::Rejected))
330}
331
332/// Details of a confirmed order
333#[derive(Debug, Clone, Deserialize)]
334pub struct OrderConfirmation {
335    /// Date and time of the confirmation
336    pub date: String,
337    /// Status of the order (accepted, rejected, etc.)
338    /// This can be null in some responses (e.g., when market is closed)
339    #[serde(deserialize_with = "deserialize_nullable_status")]
340    pub status: Status,
341    /// Reason for rejection if applicable
342    pub reason: Option<String>,
343    /// Unique identifier for the deal
344    #[serde(rename = "dealId")]
345    pub deal_id: Option<String>,
346    /// Client-generated reference for the deal
347    #[serde(rename = "dealReference")]
348    pub deal_reference: String,
349    /// Status of the deal
350    #[serde(rename = "dealStatus")]
351    pub deal_status: Option<String>,
352    /// Instrument EPIC identifier
353    pub epic: Option<String>,
354    /// Expiry date for the order
355    #[serde(rename = "expiry")]
356    pub expiry: Option<String>,
357    /// Whether a guaranteed stop was used
358    #[serde(rename = "guaranteedStop")]
359    pub guaranteed_stop: Option<bool>,
360    /// Price level of the order
361    #[serde(rename = "level")]
362    pub level: Option<f64>,
363    /// Distance for take profit
364    #[serde(rename = "limitDistance")]
365    pub limit_distance: Option<f64>,
366    /// Price level for take profit
367    #[serde(rename = "limitLevel")]
368    pub limit_level: Option<f64>,
369    /// Size/quantity of the order
370    pub size: Option<f64>,
371    /// Distance for stop loss
372    #[serde(rename = "stopDistance")]
373    pub stop_distance: Option<f64>,
374    /// Price level for stop loss
375    #[serde(rename = "stopLevel")]
376    pub stop_level: Option<f64>,
377    /// Whether a trailing stop was used
378    #[serde(rename = "trailingStop")]
379    pub trailing_stop: Option<bool>,
380    /// Direction of the order (buy or sell)
381    pub direction: Option<Direction>,
382}
383
384/// Model for updating an existing position
385#[derive(Debug, Clone, Serialize)]
386pub struct UpdatePositionRequest {
387    /// New price level for stop loss
388    #[serde(rename = "stopLevel", skip_serializing_if = "Option::is_none")]
389    pub stop_level: Option<f64>,
390    /// New price level for take profit
391    #[serde(rename = "limitLevel", skip_serializing_if = "Option::is_none")]
392    pub limit_level: Option<f64>,
393    /// Whether to enable trailing stop
394    #[serde(rename = "trailingStop", skip_serializing_if = "Option::is_none")]
395    pub trailing_stop: Option<bool>,
396    /// Distance for trailing stop
397    #[serde(
398        rename = "trailingStopDistance",
399        skip_serializing_if = "Option::is_none"
400    )]
401    pub trailing_stop_distance: Option<f64>,
402}
403
404/// Model for closing an existing position
405#[derive(Debug, Clone, Serialize)]
406pub struct ClosePositionRequest {
407    /// Unique identifier for the position to close
408    #[serde(rename = "dealId")]
409    pub deal_id: Option<String>,
410    /// Direction of the closing order (opposite to the position)
411    pub direction: Direction,
412    /// Size/quantity to close
413    pub size: f64,
414    /// Type of order to use for closing
415    #[serde(rename = "orderType")]
416    pub order_type: OrderType,
417    /// Order duration for the closing order
418    #[serde(rename = "timeInForce")]
419    pub time_in_force: TimeInForce,
420    /// Price level for limit close orders
421    #[serde(rename = "level", skip_serializing_if = "Option::is_none")]
422    pub level: Option<f64>,
423    /// Expiry date for the order
424    #[serde(rename = "expiry")]
425    pub expiry: Option<String>,
426    /// Instrument EPIC identifier
427    pub epic: Option<String>,
428
429    /// Quote identifier for the order, used for certain order types that require a specific quote
430    #[serde(rename = "quoteId")]
431    pub quote_id: Option<String>,
432}
433
434impl ClosePositionRequest {
435    /// Creates a request to close a position at market price
436    pub fn market(deal_id: String, direction: Direction, size: f64) -> Self {
437        Self {
438            deal_id: Some(deal_id),
439            direction,
440            size,
441            order_type: OrderType::Market,
442            time_in_force: TimeInForce::FillOrKill,
443            level: None,
444            expiry: None,
445            epic: None,
446            quote_id: None,
447        }
448    }
449
450    /// Creates a request to close a position at a specific price level
451    ///
452    /// This is useful for instruments that don't support market orders
453    pub fn limit(deal_id: String, direction: Direction, size: f64, level: f64) -> Self {
454        Self {
455            deal_id: Some(deal_id),
456            direction,
457            size,
458            order_type: OrderType::Limit,
459            time_in_force: TimeInForce::FillOrKill,
460            level: Some(level),
461            expiry: None,
462            epic: None,
463            quote_id: None,
464        }
465    }
466
467    /// Creates a request to close an option position by deal ID using a limit order with predefined price levels
468    ///
469    /// This is specifically designed for options trading where market orders are not supported
470    /// and a limit order with a predefined price level is required based on the direction.
471    ///
472    /// # Arguments
473    /// * `deal_id` - The ID of the deal to close
474    /// * `direction` - The direction of the closing order (opposite of the position direction)
475    /// * `size` - The size of the position to close
476    pub fn close_option_to_market_by_id(deal_id: String, direction: Direction, size: f64) -> Self {
477        let level = match direction {
478            Direction::Buy => Some(DEFAULT_ORDER_BUY_SIZE),
479            Direction::Sell => Some(DEFAULT_ORDER_SELL_SIZE),
480        };
481        Self {
482            deal_id: Some(deal_id),
483            direction,
484            size,
485            order_type: OrderType::Limit,
486            time_in_force: TimeInForce::FillOrKill,
487            level,
488            expiry: None,
489            epic: None,
490            quote_id: None,
491        }
492    }
493
494    /// Creates a request to close an option position by epic identifier using a limit order with predefined price levels
495    ///
496    /// This is specifically designed for options trading where market orders are not supported
497    /// and a limit order with a predefined price level is required based on the direction.
498    /// This method is used when the deal ID is not available but the epic and expiry are known.
499    ///
500    /// # Arguments
501    /// * `epic` - The epic identifier of the instrument
502    /// * `expiry` - The expiry date of the option
503    /// * `direction` - The direction of the closing order (opposite of the position direction)
504    /// * `size` - The size of the position to close
505    pub fn close_option_to_market_by_epic(
506        epic: String,
507        expiry: String,
508        direction: Direction,
509        size: f64,
510    ) -> Self {
511        let level = match direction {
512            Direction::Buy => Some(DEFAULT_ORDER_BUY_SIZE),
513            Direction::Sell => Some(DEFAULT_ORDER_SELL_SIZE),
514        };
515        Self {
516            deal_id: None,
517            direction,
518            size,
519            order_type: OrderType::Limit,
520            time_in_force: TimeInForce::FillOrKill,
521            level,
522            expiry: Some(expiry),
523            epic: Some(epic),
524            quote_id: None,
525        }
526    }
527}
528
529/// Response to closing a position
530#[derive(Debug, Clone, Deserialize)]
531pub struct ClosePositionResponse {
532    /// Client-generated reference for the closing deal
533    #[serde(rename = "dealReference")]
534    pub deal_reference: String,
535}
536
537/// Response to updating a position
538#[derive(Debug, Clone, Deserialize)]
539pub struct UpdatePositionResponse {
540    /// Client-generated reference for the update deal
541    #[serde(rename = "dealReference")]
542    pub deal_reference: String,
543}
544
545/// Model for creating a new working order
546#[derive(Debug, Clone, Serialize)]
547pub struct CreateWorkingOrderRequest {
548    /// Instrument EPIC identifier
549    pub epic: String,
550    /// Order direction (buy or sell)
551    pub direction: Direction,
552    /// Order size/quantity
553    pub size: f64,
554    /// Price level for the order
555    pub level: f64,
556    /// Type of working order (LIMIT or STOP)
557    #[serde(rename = "type")]
558    pub order_type: OrderType,
559    /// Order duration (how long the order remains valid)
560    #[serde(rename = "timeInForce")]
561    pub time_in_force: TimeInForce,
562    /// Whether to use a guaranteed stop
563    #[serde(rename = "guaranteedStop", skip_serializing_if = "Option::is_none")]
564    pub guaranteed_stop: Option<bool>,
565    /// Price level for stop loss
566    #[serde(rename = "stopLevel", skip_serializing_if = "Option::is_none")]
567    pub stop_level: Option<f64>,
568    /// Distance for stop loss
569    #[serde(rename = "stopDistance", skip_serializing_if = "Option::is_none")]
570    pub stop_distance: Option<f64>,
571    /// Price level for take profit
572    #[serde(rename = "limitLevel", skip_serializing_if = "Option::is_none")]
573    pub limit_level: Option<f64>,
574    /// Distance for take profit
575    #[serde(rename = "limitDistance", skip_serializing_if = "Option::is_none")]
576    pub limit_distance: Option<f64>,
577    /// Expiry date for GTD orders
578    #[serde(rename = "goodTillDate", skip_serializing_if = "Option::is_none")]
579    pub good_till_date: Option<String>,
580    /// Client-generated reference for the deal
581    #[serde(rename = "dealReference", skip_serializing_if = "Option::is_none")]
582    pub deal_reference: Option<String>,
583    /// Currency code for the order (e.g., "USD", "EUR")
584    #[serde(rename = "currencyCode", skip_serializing_if = "Option::is_none")]
585    pub currency_code: Option<String>,
586}
587
588impl CreateWorkingOrderRequest {
589    /// Creates a new limit working order
590    pub fn limit(epic: String, direction: Direction, size: f64, level: f64) -> Self {
591        Self {
592            epic,
593            direction,
594            size,
595            level,
596            order_type: OrderType::Limit,
597            time_in_force: TimeInForce::GoodTillCancelled,
598            guaranteed_stop: None,
599            stop_level: None,
600            stop_distance: None,
601            limit_level: None,
602            limit_distance: None,
603            good_till_date: None,
604            deal_reference: None,
605            currency_code: None,
606        }
607    }
608
609    /// Creates a new stop working order
610    pub fn stop(epic: String, direction: Direction, size: f64, level: f64) -> Self {
611        Self {
612            epic,
613            direction,
614            size,
615            level,
616            order_type: OrderType::Stop,
617            time_in_force: TimeInForce::GoodTillCancelled,
618            guaranteed_stop: None,
619            stop_level: None,
620            stop_distance: None,
621            limit_level: None,
622            limit_distance: None,
623            good_till_date: None,
624            deal_reference: None,
625            currency_code: None,
626        }
627    }
628
629    /// Adds a stop loss to the working order
630    pub fn with_stop_loss(mut self, stop_level: f64) -> Self {
631        self.stop_level = Some(stop_level);
632        self
633    }
634
635    /// Adds a take profit to the working order
636    pub fn with_take_profit(mut self, limit_level: f64) -> Self {
637        self.limit_level = Some(limit_level);
638        self
639    }
640
641    /// Adds a reference to the working order
642    pub fn with_reference(mut self, reference: String) -> Self {
643        self.deal_reference = Some(reference);
644        self
645    }
646
647    /// Sets the order to expire at a specific date
648    pub fn expires_at(mut self, date: String) -> Self {
649        self.time_in_force = TimeInForce::GoodTillDate;
650        self.good_till_date = Some(date);
651        self
652    }
653}
654
655/// Response to working order creation
656#[derive(Debug, Clone, Deserialize)]
657pub struct CreateWorkingOrderResponse {
658    /// Client-generated reference for the deal
659    #[serde(rename = "dealReference")]
660    pub deal_reference: String,
661}