Skip to main content

ctrader_connector/fix/
messages.rs

1//! Typed messages of the FIX 4.4 sessions and their conversion to and from fields.
2//!
3//! Every message the library sends or understands has a struct here and a variant in
4//! [`Message`]. A message is parsed whole: a required field that is absent or a value of the
5//! wrong form rejects the message with a typed error instead of yielding a partial value.
6//! Prices and quantities are decimals, symbols, orders and positions are identified by their
7//! typed ids.
8//!
9//! ```
10//! use ctrader_connector::common::time::Timestamp;
11//! use ctrader_connector::fix::codec::{Header, decode, encode};
12//! use ctrader_connector::fix::messages::{Message, TestRequest};
13//!
14//! let message = Message::from(TestRequest {
15//!     test_req_id: "ping".to_owned(),
16//! });
17//! let header = Header::new("", "demo.broker.1", "CSERVER", 2, Timestamp::EPOCH);
18//! let mut bytes = encode(&message.to_frame(header))?;
19//! let frame = decode(&mut bytes)?.expect("whole message");
20//! assert_eq!(Message::from_frame(&frame)?, message);
21//! # Ok::<(), ctrader_connector::common::errors::FixError>(())
22//! ```
23
24use std::str::FromStr;
25
26use rust_decimal::Decimal;
27
28use crate::common::config::FixPassword;
29use crate::common::decimals::{Price, Volume};
30use crate::common::errors::FixError;
31use crate::common::ids::{OrderId, PositionId, SymbolId};
32use crate::common::time::Timestamp;
33use crate::fix::codec::{Field, Frame, Header, format_time, parse_time};
34
35trait Wire: Sized {
36    fn to_wire(&self) -> String;
37    fn from_wire(text: &str) -> Option<Self>;
38}
39
40impl Wire for String {
41    fn to_wire(&self) -> String {
42        self.clone()
43    }
44
45    fn from_wire(text: &str) -> Option<Self> {
46        Some(text.to_owned())
47    }
48}
49
50impl Wire for bool {
51    fn to_wire(&self) -> String {
52        if *self { "Y" } else { "N" }.to_owned()
53    }
54
55    fn from_wire(text: &str) -> Option<Self> {
56        match text {
57            "Y" => Some(true),
58            "N" => Some(false),
59            _ => None,
60        }
61    }
62}
63
64impl Wire for Timestamp {
65    fn to_wire(&self) -> String {
66        format_time(*self, self.as_millis() % 1_000 != 0)
67    }
68
69    fn from_wire(text: &str) -> Option<Self> {
70        parse_time(text)
71    }
72}
73
74impl Wire for FixPassword {
75    fn to_wire(&self) -> String {
76        self.expose().to_owned()
77    }
78
79    fn from_wire(text: &str) -> Option<Self> {
80        Self::new(text).ok()
81    }
82}
83
84macro_rules! wire_from_str {
85    ($($ty:ty),*) => {
86        $(impl Wire for $ty {
87            fn to_wire(&self) -> String {
88                self.to_string()
89            }
90
91            fn from_wire(text: &str) -> Option<Self> {
92                <$ty>::from_str(text).ok()
93            }
94        })*
95    };
96}
97
98wire_from_str!(
99    u32, u64, Decimal, Price, Volume, SymbolId, OrderId, PositionId
100);
101
102macro_rules! wire_enum {
103    ($(#[$doc:meta])* $name:ident { $($(#[$vdoc:meta])* $variant:ident => $wire:literal,)* }) => {
104        $(#[$doc])*
105        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
106        pub enum $name {
107            $($(#[$vdoc])* $variant,)*
108        }
109
110        impl $name {
111            /// Returns the value the wire carries.
112            #[must_use]
113            pub const fn as_str(self) -> &'static str {
114                match self {
115                    $(Self::$variant => $wire,)*
116                }
117            }
118        }
119
120        impl Wire for $name {
121            fn to_wire(&self) -> String {
122                self.as_str().to_owned()
123            }
124
125            fn from_wire(text: &str) -> Option<Self> {
126                match text {
127                    $($wire => Some(Self::$variant),)*
128                    _ => None,
129                }
130            }
131        }
132    };
133}
134
135wire_enum! {
136    /// Side of an order (54).
137    Side {
138        /// Buy.
139        Buy => "1",
140        /// Sell.
141        Sell => "2",
142    }
143}
144
145wire_enum! {
146    /// Type of an order (40).
147    OrderKind {
148        /// Executed at once at the price of the market.
149        Market => "1",
150        /// Executed at the limit price or better.
151        Limit => "2",
152        /// Becomes a market order once the stop price is reached.
153        Stop => "3",
154        /// Becomes a limit order once the stop price is reached. The server offers no such
155        /// order over FIX: the kind is read from a report and no typed request sends it.
156        StopLimit => "4",
157    }
158}
159
160wire_enum! {
161    /// How long an order stays in force (59).
162    TimeInForce {
163        /// Until it is cancelled.
164        GoodTillCancel => "1",
165        /// Filled at once as far as possible, the rest is cancelled.
166        ImmediateOrCancel => "3",
167        /// Until the expiry time.
168        GoodTillDate => "6",
169    }
170}
171
172wire_enum! {
173    /// What an execution report tells (150).
174    ExecType {
175        /// The order was accepted.
176        New => "0",
177        /// The order was cancelled.
178        Canceled => "4",
179        /// The order was replaced.
180        Replaced => "5",
181        /// The order was rejected.
182        Rejected => "8",
183        /// The order expired.
184        Expired => "C",
185        /// The order was filled, wholly or in part.
186        Trade => "F",
187        /// The report answers a status request.
188        OrderStatus => "I",
189    }
190}
191
192wire_enum! {
193    /// State of an order (39).
194    OrderStatus {
195        /// Accepted and not filled.
196        New => "0",
197        /// Filled in part.
198        PartiallyFilled => "1",
199        /// Filled.
200        Filled => "2",
201        /// Cancelled.
202        Canceled => "4",
203        /// Replaced.
204        Replaced => "5",
205        /// Rejected.
206        Rejected => "8",
207        /// Expired.
208        Expired => "C",
209    }
210}
211
212wire_enum! {
213    /// Request a cancel reject answers (434).
214    CancelRejectResponse {
215        /// An order cancel request.
216        Cancel => "1",
217        /// An order cancel/replace request.
218        Replace => "2",
219    }
220}
221
222wire_enum! {
223    /// Depth of the market data asked for (264).
224    MarketDepth {
225        /// The full book.
226        Full => "0",
227        /// The best bid and the best offer only.
228        Spot => "1",
229    }
230}
231
232wire_enum! {
233    /// Side of a market data entry (269).
234    BookSide {
235        /// Bid.
236        Bid => "0",
237        /// Offer.
238        Offer => "1",
239    }
240}
241
242struct Reader<'a> {
243    kind: &'static str,
244    fields: &'a [Field],
245}
246
247impl<'a> Reader<'a> {
248    const fn new(kind: &'static str, fields: &'a [Field]) -> Self {
249        Self { kind, fields }
250    }
251
252    fn missing(&self, tag: u32) -> FixError {
253        FixError::MissingField {
254            msg_type: self.kind.to_owned(),
255            tag,
256        }
257    }
258
259    fn invalid(&self, tag: u32) -> FixError {
260        FixError::InvalidField {
261            msg_type: self.kind.to_owned(),
262            tag,
263        }
264    }
265
266    fn text(&self, tag: u32) -> Option<&'a str> {
267        self.fields
268            .iter()
269            .find(|field| field.tag == tag)
270            .map(|field| field.value.as_str())
271    }
272
273    fn optional<T: Wire>(&self, tag: u32) -> Result<Option<T>, FixError> {
274        self.text(tag)
275            .map(|text| T::from_wire(text).ok_or_else(|| self.invalid(tag)))
276            .transpose()
277    }
278
279    fn required<T: Wire>(&self, tag: u32) -> Result<T, FixError> {
280        self.optional(tag)?.ok_or_else(|| self.missing(tag))
281    }
282
283    fn lax<T: Wire>(&self, tag: u32) -> Option<T> {
284        self.text(tag).and_then(T::from_wire)
285    }
286
287    fn group(&self, count_tag: u32, members: &[u32]) -> Result<Vec<Self>, FixError> {
288        let Some(at) = self.fields.iter().position(|field| field.tag == count_tag) else {
289            return Ok(Vec::new());
290        };
291        let count: u32 = self.required(count_tag)?;
292        let rest = self.fields.get(at.saturating_add(1)..).unwrap_or(&[]);
293        let length = rest
294            .iter()
295            .position(|field| !members.contains(&field.tag))
296            .unwrap_or(rest.len());
297        let inside = rest.get(..length).unwrap_or(rest);
298        let delimiter = members.first().copied().unwrap_or(0);
299        let mut entries = Vec::new();
300        let mut start = 0_usize;
301        for (index, field) in inside.iter().enumerate() {
302            if field.tag == delimiter && index > 0 {
303                entries.push(Self::new(
304                    self.kind,
305                    inside.get(start..index).unwrap_or(&[]),
306                ));
307                start = index;
308            }
309        }
310        match inside.first() {
311            Some(first) if first.tag == delimiter => {
312                entries.push(Self::new(self.kind, inside.get(start..).unwrap_or(&[])));
313            }
314            Some(_) => return Err(self.invalid(count_tag)),
315            None => {}
316        }
317        if u32::try_from(entries.len()).ok() == Some(count) {
318            Ok(entries)
319        } else {
320            Err(self.invalid(count_tag))
321        }
322    }
323}
324
325fn put<T: Wire>(out: &mut Vec<Field>, tag: u32, value: &T) {
326    out.push(Field::new(tag, value.to_wire()));
327}
328
329fn put_optional<T: Wire>(out: &mut Vec<Field>, tag: u32, value: Option<&T>) {
330    if let Some(value) = value {
331        put(out, tag, value);
332    }
333}
334
335fn put_count(out: &mut Vec<Field>, tag: u32, count: usize) {
336    out.push(Field::new(tag, count.to_string()));
337}
338
339macro_rules! flat {
340    (
341        $(#[$doc:meta])* $name:ident, $kind:literal {
342            $($(#[$fdoc:meta])* $mode:ident $field:ident: $ty:ty = $tag:literal,)*
343        }
344    ) => {
345        $(#[$doc])*
346        #[derive(Debug, Clone, PartialEq, Eq)]
347        pub struct $name {
348            $($(#[$fdoc])* pub $field: flat!(@ty $mode $ty),)*
349        }
350
351        impl $name {
352            /// Type of the message (35).
353            pub const MSG_TYPE: &'static str = $kind;
354
355            fn write(&self, out: &mut Vec<Field>) {
356                $(flat!(@put $mode out, $tag, self.$field);)*
357            }
358
359            fn read(reader: &Reader<'_>) -> Result<Self, FixError> {
360                Ok(Self {
361                    $($field: flat!(@get $mode reader, $tag),)*
362                })
363            }
364        }
365    };
366    (@ty req $ty:ty) => { $ty };
367    (@ty opt $ty:ty) => { Option<$ty> };
368    (@ty lax $ty:ty) => { Option<$ty> };
369    (@put req $out:ident, $tag:literal, $value:expr) => { put($out, $tag, &$value) };
370    (@put opt $out:ident, $tag:literal, $value:expr) => { put_optional($out, $tag, $value.as_ref()) };
371    (@put lax $out:ident, $tag:literal, $value:expr) => { put_optional($out, $tag, $value.as_ref()) };
372    (@get req $reader:ident, $tag:literal) => { $reader.required($tag)? };
373    (@get opt $reader:ident, $tag:literal) => { $reader.optional($tag)? };
374    (@get lax $reader:ident, $tag:literal) => { $reader.lax($tag) };
375}
376
377flat! {
378    /// Heartbeat (0): sent when nothing else was sent for the heartbeat interval, and in
379    /// answer to a test request.
380    Heartbeat, "0" {
381        /// Identifier of the test request the heartbeat answers (112).
382        opt test_req_id: String = 112,
383    }
384}
385
386flat! {
387    /// Test request (1): asks the other side for a heartbeat.
388    TestRequest, "1" {
389        /// Identifier the answering heartbeat repeats (112).
390        req test_req_id: String = 112,
391    }
392}
393
394flat! {
395    /// Resend request (2): asks the other side to send a range of messages again.
396    ResendRequest, "2" {
397        /// First sequence number of the range (7).
398        req begin_seq_no: u64 = 7,
399        /// Last sequence number of the range; zero stands for every message after the
400        /// first (16).
401        req end_seq_no: u64 = 16,
402    }
403}
404
405flat! {
406    /// Reject (3): the other side could not process a message of the session level.
407    Reject, "3" {
408        /// Sequence number of the rejected message (45).
409        req ref_seq_num: u64 = 45,
410        /// Explanation (58).
411        opt text: String = 58,
412        /// Tag the rejection is about (371).
413        opt ref_tag_id: u32 = 371,
414        /// Type of the rejected message (372).
415        opt ref_msg_type: String = 372,
416        /// Code of the reason (373).
417        opt reason: u32 = 373,
418    }
419}
420
421flat! {
422    /// Sequence reset (4): moves the expected sequence number forward.
423    SequenceReset, "4" {
424        /// Tells whether the reset fills a gap in answer to a resend request (123).
425        opt gap_fill: bool = 123,
426        /// Sequence number of the next message (36).
427        req new_seq_no: u64 = 36,
428    }
429}
430
431flat! {
432    /// Logout (5): ends the session, or refuses a logon.
433    Logout, "5" {
434        /// Explanation (58).
435        opt text: String = 58,
436    }
437}
438
439flat! {
440    /// Logon (A): opens a session.
441    Logon, "A" {
442        /// Encryption method; zero, none, is the one supported (98).
443        req encrypt_method: u32 = 98,
444        /// Heartbeat interval in seconds (108).
445        req heart_bt_int: u32 = 108,
446        /// Tells whether both sides restart their sequence numbers at one (141).
447        opt reset_seq_num: bool = 141,
448        /// Login of the account (553).
449        opt username: String = 553,
450        /// Password of the account (554).
451        opt password: FixPassword = 554,
452    }
453}
454
455flat! {
456    /// Business message reject (j): the server refused a message of the application level.
457    BusinessReject, "j" {
458        /// Sequence number of the refused message (45).
459        opt ref_seq_num: u64 = 45,
460        /// Type of the refused message (372).
461        opt ref_msg_type: String = 372,
462        /// Identifier the refused message carried, such as its client order id (379).
463        opt ref_id: String = 379,
464        /// Code of the reason (380).
465        opt reason: u32 = 380,
466        /// Explanation (58).
467        opt text: String = 58,
468    }
469}
470
471flat! {
472    /// Market data request reject (Y).
473    MarketDataReject, "Y" {
474        /// Identifier of the refused request (262).
475        req md_req_id: String = 262,
476        /// Code of the reason; zero stands for an unknown symbol (281).
477        opt reason: u32 = 281,
478        /// Explanation (58).
479        opt text: String = 58,
480    }
481}
482
483flat! {
484    /// Security list request (x).
485    SecurityListRequest, "x" {
486        /// Identifier of the request (320).
487        req security_req_id: String = 320,
488        /// Kind of the request; zero asks for the symbols (559).
489        req request_type: u32 = 559,
490        /// Symbol to restrict the list to (55).
491        opt symbol: SymbolId = 55,
492    }
493}
494
495flat! {
496    /// New order single (D).
497    NewOrderSingle, "D" {
498        /// Identifier the client gives the order (11).
499        req cl_ord_id: String = 11,
500        /// Symbol (55).
501        req symbol: SymbolId = 55,
502        /// Side (54).
503        req side: Side = 54,
504        /// Time the client created the order (60).
505        req transact_time: Timestamp = 60,
506        /// Quantity (38).
507        req order_qty: Volume = 38,
508        /// Type (40).
509        req ord_type: OrderKind = 40,
510        /// Limit price (44).
511        opt price: Price = 44,
512        /// Stop price (99).
513        opt stop_px: Price = 99,
514        /// Time in force (59).
515        opt time_in_force: TimeInForce = 59,
516        /// Expiry time (126).
517        opt expire_time: Timestamp = 126,
518        /// Position the order changes, on hedged accounts (721).
519        opt position_id: PositionId = 721,
520        /// Label of the order (494).
521        opt designation: String = 494,
522    }
523}
524
525flat! {
526    /// Execution report (8): the state of an order after an event.
527    ExecutionReport, "8" {
528        /// Identifier the server gave the order (37).
529        lax order_id: OrderId = 37,
530        /// Identifier the client gave the order (11).
531        opt cl_ord_id: String = 11,
532        /// Client identifier of the order a cancel or replace request named (41).
533        opt orig_cl_ord_id: String = 41,
534        /// Number of reports that answer a mass status request (911).
535        opt tot_num_reports: u32 = 911,
536        /// What the report tells (150).
537        req exec_type: ExecType = 150,
538        /// State of the order (39).
539        req ord_status: OrderStatus = 39,
540        /// Symbol (55).
541        opt symbol: SymbolId = 55,
542        /// Side (54).
543        opt side: Side = 54,
544        /// Quantity (38).
545        opt order_qty: Volume = 38,
546        /// Type (40).
547        opt ord_type: OrderKind = 40,
548        /// Limit price (44).
549        opt price: Price = 44,
550        /// Stop price (99).
551        opt stop_px: Price = 99,
552        /// Time in force (59).
553        opt time_in_force: TimeInForce = 59,
554        /// Expiry time (126).
555        opt expire_time: Timestamp = 126,
556        /// Quantity of the last fill (32).
557        opt last_qty: Volume = 32,
558        /// Price of the last fill (31).
559        opt last_px: Price = 31,
560        /// Quantity still open (151).
561        opt leaves_qty: Volume = 151,
562        /// Quantity filled so far (14).
563        opt cum_qty: Volume = 14,
564        /// Average price of the fills (6).
565        opt avg_px: Price = 6,
566        /// Time of the event (60).
567        opt transact_time: Timestamp = 60,
568        /// Explanation (58).
569        opt text: String = 58,
570        /// Code of the reason of a rejection (103).
571        opt ord_rej_reason: u32 = 103,
572        /// Position the order opened or changed (721).
573        opt position_id: PositionId = 721,
574        /// Label of the order (494).
575        opt designation: String = 494,
576        /// Identifier of the mass status request the report answers (584).
577        opt mass_status_req_id: String = 584,
578        /// Take profit as a price (1000).
579        opt absolute_tp: Price = 1000,
580        /// Take profit as a distance from the entry price (1001).
581        opt relative_tp: Decimal = 1001,
582        /// Stop loss as a price (1002).
583        opt absolute_sl: Price = 1002,
584        /// Stop loss as a distance from the entry price (1003).
585        opt relative_sl: Decimal = 1003,
586        /// Tells whether the stop loss trails the price (1004).
587        opt trailing_sl: bool = 1004,
588        /// Code of the trigger method of the stop loss (1005).
589        opt trigger_method_sl: u32 = 1005,
590        /// Tells whether the stop loss is guaranteed (1006).
591        opt guaranteed_sl: bool = 1006,
592    }
593}
594
595flat! {
596    /// Order status request (H).
597    OrderStatusRequest, "H" {
598        /// Client identifier of the order (11).
599        req cl_ord_id: String = 11,
600        /// Side of the order (54).
601        opt side: Side = 54,
602    }
603}
604
605flat! {
606    /// Order mass status request (AF).
607    OrderMassStatusRequest, "AF" {
608        /// Identifier of the request (584).
609        req mass_status_req_id: String = 584,
610        /// Kind of the request; seven asks for every order (585).
611        req request_type: u32 = 585,
612        /// Earliest issue time of the orders asked for (225).
613        opt issue_date: Timestamp = 225,
614    }
615}
616
617flat! {
618    /// Request for positions (AN).
619    RequestForPositions, "AN" {
620        /// Identifier of the request (710).
621        req pos_req_id: String = 710,
622        /// Position to restrict the answer to (721).
623        opt position_id: PositionId = 721,
624    }
625}
626
627flat! {
628    /// Order cancel request (F).
629    OrderCancelRequest, "F" {
630        /// Client identifier of the order to cancel (41).
631        req orig_cl_ord_id: String = 41,
632        /// Server identifier of the order to cancel (37).
633        opt order_id: OrderId = 37,
634        /// Client identifier of the request (11).
635        req cl_ord_id: String = 11,
636    }
637}
638
639flat! {
640    /// Order cancel reject (9).
641    OrderCancelReject, "9" {
642        /// Server identifier of the order (37).
643        lax order_id: OrderId = 37,
644        /// Client identifier of the refused request (11).
645        req cl_ord_id: String = 11,
646        /// Client identifier of the order the request named (41).
647        opt orig_cl_ord_id: String = 41,
648        /// State of the order (39).
649        req ord_status: OrderStatus = 39,
650        /// Request the reject answers (434).
651        req response_to: CancelRejectResponse = 434,
652        /// Explanation (58).
653        opt text: String = 58,
654    }
655}
656
657flat! {
658    /// Order cancel/replace request (G).
659    OrderCancelReplaceRequest, "G" {
660        /// Client identifier of the order to change (41).
661        req orig_cl_ord_id: String = 41,
662        /// Server identifier of the order to change (37).
663        opt order_id: OrderId = 37,
664        /// Client identifier of the request (11).
665        req cl_ord_id: String = 11,
666        /// New quantity (38).
667        req order_qty: Volume = 38,
668        /// New limit price (44).
669        opt price: Price = 44,
670        /// New stop price (99).
671        opt stop_px: Price = 99,
672        /// New expiry time (126).
673        opt expire_time: Timestamp = 126,
674    }
675}
676
677const TAG_SYMBOL: u32 = 55;
678const TAG_LONG_QTY: u32 = 704;
679const TAG_SHORT_QTY: u32 = 705;
680const TAG_NO_RELATED_SYM: u32 = 146;
681const TAG_MD_REQ_ID: u32 = 262;
682const TAG_SUBSCRIPTION: u32 = 263;
683const TAG_MARKET_DEPTH: u32 = 264;
684const TAG_UPDATE_TYPE: u32 = 265;
685const TAG_NO_ENTRY_TYPES: u32 = 267;
686const TAG_NO_ENTRIES: u32 = 268;
687const TAG_ENTRY_TYPE: u32 = 269;
688const TAG_ENTRY_PX: u32 = 270;
689const TAG_ENTRY_SIZE: u32 = 271;
690const TAG_ENTRY_ID: u32 = 278;
691const TAG_UPDATE_ACTION: u32 = 279;
692const TAG_QUOTE_ENTRY_ID: u32 = 299;
693const TAG_SECURITY_REQ_ID: u32 = 320;
694const TAG_SECURITY_RESPONSE_ID: u32 = 322;
695const TAG_SECURITY_RESULT: u32 = 560;
696const TAG_NO_POSITIONS: u32 = 702;
697const TAG_POS_REQ_ID: u32 = 710;
698const TAG_POSITION_ID: u32 = 721;
699const TAG_TOTAL_REPORTS: u32 = 727;
700const TAG_POS_REQ_RESULT: u32 = 728;
701const TAG_SETTL_PRICE: u32 = 730;
702const TAG_SYMBOL_NAME: u32 = 1007;
703const TAG_SYMBOL_DIGITS: u32 = 1008;
704const TAG_ABSOLUTE_TP: u32 = 1000;
705const TAG_ABSOLUTE_SL: u32 = 1002;
706const TAG_TRAILING_SL: u32 = 1004;
707const TAG_TRIGGER_METHOD_SL: u32 = 1005;
708const TAG_GUARANTEED_SL: u32 = 1006;
709
710const SUBSCRIBE: &str = "1";
711const UNSUBSCRIBE: &str = "2";
712const INCREMENTAL_REFRESH: &str = "1";
713const ACTION_NEW: &str = "0";
714const ACTION_DELETE: &str = "2";
715
716/// Market data request (V): subscribes to or unsubscribes from prices of symbols.
717#[derive(Debug, Clone, PartialEq, Eq)]
718pub struct MarketDataRequest {
719    /// Identifier of the request; an unsubscription repeats the one of the subscription (262).
720    pub md_req_id: String,
721    /// Tells whether the request subscribes; otherwise it unsubscribes (263).
722    pub subscribe: bool,
723    /// Depth asked for (264).
724    pub depth: MarketDepth,
725    /// Symbols (146, 55).
726    pub symbols: Vec<SymbolId>,
727    /// Sides asked for (267, 269).
728    pub sides: Vec<BookSide>,
729}
730
731impl MarketDataRequest {
732    /// Type of the message (35).
733    pub const MSG_TYPE: &'static str = "V";
734
735    fn write(&self, out: &mut Vec<Field>) {
736        put(out, TAG_MD_REQ_ID, &self.md_req_id);
737        let subscription = if self.subscribe {
738            SUBSCRIBE
739        } else {
740            UNSUBSCRIBE
741        };
742        out.push(Field::new(TAG_SUBSCRIPTION, subscription));
743        put(out, TAG_MARKET_DEPTH, &self.depth);
744        out.push(Field::new(TAG_UPDATE_TYPE, INCREMENTAL_REFRESH));
745        put_count(out, TAG_NO_RELATED_SYM, self.symbols.len());
746        for symbol in &self.symbols {
747            put(out, TAG_SYMBOL, symbol);
748        }
749        put_count(out, TAG_NO_ENTRY_TYPES, self.sides.len());
750        for side in &self.sides {
751            put(out, TAG_ENTRY_TYPE, side);
752        }
753    }
754
755    fn read(reader: &Reader<'_>) -> Result<Self, FixError> {
756        let subscribe = match reader.required::<String>(TAG_SUBSCRIPTION)?.as_str() {
757            SUBSCRIBE => true,
758            UNSUBSCRIBE => false,
759            _ => return Err(reader.invalid(TAG_SUBSCRIPTION)),
760        };
761        Ok(Self {
762            md_req_id: reader.required(TAG_MD_REQ_ID)?,
763            subscribe,
764            depth: reader.required(TAG_MARKET_DEPTH)?,
765            symbols: reader
766                .group(TAG_NO_RELATED_SYM, &[TAG_SYMBOL])?
767                .iter()
768                .map(|entry| entry.required(TAG_SYMBOL))
769                .collect::<Result<_, _>>()?,
770            sides: reader
771                .group(TAG_NO_ENTRY_TYPES, &[TAG_ENTRY_TYPE])?
772                .iter()
773                .map(|entry| entry.required(TAG_ENTRY_TYPE))
774                .collect::<Result<_, _>>()?,
775        })
776    }
777}
778
779/// One price of a market data snapshot.
780#[derive(Debug, Clone, PartialEq, Eq)]
781pub struct SnapshotEntry {
782    /// Side (269).
783    pub side: BookSide,
784    /// Price (270).
785    pub price: Price,
786    /// Quantity offered at the price; absent for spot prices (271).
787    pub size: Option<Volume>,
788    /// Identifier of the entry in the book; absent for spot prices (278).
789    pub id: Option<String>,
790}
791
792/// Market data snapshot (W): the prices of one symbol.
793#[derive(Debug, Clone, PartialEq, Eq)]
794pub struct MarketDataSnapshot {
795    /// Identifier of the request the snapshot belongs to (262).
796    pub md_req_id: Option<String>,
797    /// Symbol (55).
798    pub symbol: SymbolId,
799    /// Prices (268).
800    pub entries: Vec<SnapshotEntry>,
801}
802
803impl MarketDataSnapshot {
804    /// Type of the message (35).
805    pub const MSG_TYPE: &'static str = "W";
806
807    fn write(&self, out: &mut Vec<Field>) {
808        put_optional(out, TAG_MD_REQ_ID, self.md_req_id.as_ref());
809        put(out, TAG_SYMBOL, &self.symbol);
810        put_count(out, TAG_NO_ENTRIES, self.entries.len());
811        for entry in &self.entries {
812            put(out, TAG_ENTRY_TYPE, &entry.side);
813            put(out, TAG_ENTRY_PX, &entry.price);
814            put_optional(out, TAG_ENTRY_SIZE, entry.size.as_ref());
815            put_optional(out, TAG_ENTRY_ID, entry.id.as_ref());
816        }
817    }
818
819    fn read(reader: &Reader<'_>) -> Result<Self, FixError> {
820        let members = [
821            TAG_ENTRY_TYPE,
822            TAG_QUOTE_ENTRY_ID,
823            TAG_ENTRY_PX,
824            TAG_ENTRY_SIZE,
825            TAG_ENTRY_ID,
826        ];
827        Ok(Self {
828            md_req_id: reader.optional(TAG_MD_REQ_ID)?,
829            symbol: reader.required(TAG_SYMBOL)?,
830            entries: reader
831                .group(TAG_NO_ENTRIES, &members)?
832                .iter()
833                .map(|entry| {
834                    Ok(SnapshotEntry {
835                        side: entry.required(TAG_ENTRY_TYPE)?,
836                        price: entry.required(TAG_ENTRY_PX)?,
837                        size: entry.optional(TAG_ENTRY_SIZE)?,
838                        id: entry.optional(TAG_ENTRY_ID)?,
839                    })
840                })
841                .collect::<Result<_, FixError>>()?,
842        })
843    }
844}
845
846/// One change of a book.
847#[derive(Debug, Clone, PartialEq, Eq)]
848pub enum BookUpdate {
849    /// A new entry.
850    New {
851        /// Side (269).
852        side: BookSide,
853        /// Identifier of the entry in the book (278).
854        id: String,
855        /// Symbol (55).
856        symbol: SymbolId,
857        /// Price (270).
858        price: Price,
859        /// Quantity offered at the price (271).
860        size: Option<Volume>,
861    },
862    /// The removal of an entry.
863    Delete {
864        /// Identifier of the entry in the book (278).
865        id: String,
866        /// Symbol (55).
867        symbol: SymbolId,
868    },
869}
870
871/// Market data incremental refresh (X): changes of books.
872#[derive(Debug, Clone, PartialEq, Eq)]
873pub struct MarketDataIncremental {
874    /// Identifier of the request the changes belong to (262).
875    pub md_req_id: Option<String>,
876    /// Changes in the order they apply (268).
877    pub entries: Vec<BookUpdate>,
878}
879
880impl MarketDataIncremental {
881    /// Type of the message (35).
882    pub const MSG_TYPE: &'static str = "X";
883
884    fn write(&self, out: &mut Vec<Field>) {
885        put_optional(out, TAG_MD_REQ_ID, self.md_req_id.as_ref());
886        put_count(out, TAG_NO_ENTRIES, self.entries.len());
887        for entry in &self.entries {
888            match entry {
889                BookUpdate::New {
890                    side,
891                    id,
892                    symbol,
893                    price,
894                    size,
895                } => {
896                    out.push(Field::new(TAG_UPDATE_ACTION, ACTION_NEW));
897                    put(out, TAG_ENTRY_TYPE, side);
898                    put(out, TAG_ENTRY_ID, id);
899                    put(out, TAG_SYMBOL, symbol);
900                    put(out, TAG_ENTRY_PX, price);
901                    put_optional(out, TAG_ENTRY_SIZE, size.as_ref());
902                }
903                BookUpdate::Delete { id, symbol } => {
904                    out.push(Field::new(TAG_UPDATE_ACTION, ACTION_DELETE));
905                    put(out, TAG_ENTRY_ID, id);
906                    put(out, TAG_SYMBOL, symbol);
907                }
908            }
909        }
910    }
911
912    fn read(reader: &Reader<'_>) -> Result<Self, FixError> {
913        let members = [
914            TAG_UPDATE_ACTION,
915            TAG_ENTRY_TYPE,
916            TAG_ENTRY_ID,
917            TAG_SYMBOL,
918            TAG_ENTRY_PX,
919            TAG_ENTRY_SIZE,
920        ];
921        Ok(Self {
922            md_req_id: reader.optional(TAG_MD_REQ_ID)?,
923            entries: reader
924                .group(TAG_NO_ENTRIES, &members)?
925                .iter()
926                .map(|entry| {
927                    let id = entry.required(TAG_ENTRY_ID)?;
928                    let symbol = entry.required(TAG_SYMBOL)?;
929                    match entry.required::<String>(TAG_UPDATE_ACTION)?.as_str() {
930                        ACTION_NEW => Ok(BookUpdate::New {
931                            side: entry.required(TAG_ENTRY_TYPE)?,
932                            id,
933                            symbol,
934                            price: entry.required(TAG_ENTRY_PX)?,
935                            size: entry.optional(TAG_ENTRY_SIZE)?,
936                        }),
937                        ACTION_DELETE => Ok(BookUpdate::Delete { id, symbol }),
938                        _ => Err(entry.invalid(TAG_UPDATE_ACTION)),
939                    }
940                })
941                .collect::<Result<_, FixError>>()?,
942        })
943    }
944}
945
946/// One symbol of a security list.
947#[derive(Debug, Clone, PartialEq, Eq)]
948pub struct SecurityEntry {
949    /// Identifier of the symbol (55).
950    pub symbol: SymbolId,
951    /// Name of the symbol (1007).
952    pub name: Option<String>,
953    /// Number of decimal places of its prices (1008).
954    pub digits: Option<u32>,
955}
956
957/// Security list (y): the symbols of the account.
958#[derive(Debug, Clone, PartialEq, Eq)]
959pub struct SecurityList {
960    /// Identifier of the request the list answers (320).
961    pub security_req_id: String,
962    /// Identifier the server gave the answer (322).
963    pub security_response_id: String,
964    /// Code of the result; zero stands for a valid request (560).
965    pub result: u32,
966    /// Symbols (146).
967    pub symbols: Vec<SecurityEntry>,
968}
969
970impl SecurityList {
971    /// Type of the message (35).
972    pub const MSG_TYPE: &'static str = "y";
973
974    fn write(&self, out: &mut Vec<Field>) {
975        put(out, TAG_SECURITY_REQ_ID, &self.security_req_id);
976        put(out, TAG_SECURITY_RESPONSE_ID, &self.security_response_id);
977        put(out, TAG_SECURITY_RESULT, &self.result);
978        if !self.symbols.is_empty() {
979            put_count(out, TAG_NO_RELATED_SYM, self.symbols.len());
980        }
981        for entry in &self.symbols {
982            put(out, TAG_SYMBOL, &entry.symbol);
983            put_optional(out, TAG_SYMBOL_NAME, entry.name.as_ref());
984            put_optional(out, TAG_SYMBOL_DIGITS, entry.digits.as_ref());
985        }
986    }
987
988    fn read(reader: &Reader<'_>) -> Result<Self, FixError> {
989        let members = [TAG_SYMBOL, TAG_SYMBOL_NAME, TAG_SYMBOL_DIGITS];
990        Ok(Self {
991            security_req_id: reader.required(TAG_SECURITY_REQ_ID)?,
992            security_response_id: reader.required(TAG_SECURITY_RESPONSE_ID)?,
993            result: reader.required(TAG_SECURITY_RESULT)?,
994            symbols: reader
995                .group(TAG_NO_RELATED_SYM, &members)?
996                .iter()
997                .map(|entry| {
998                    Ok(SecurityEntry {
999                        symbol: entry.required(TAG_SYMBOL)?,
1000                        name: entry.optional(TAG_SYMBOL_NAME)?,
1001                        digits: entry.optional(TAG_SYMBOL_DIGITS)?,
1002                    })
1003                })
1004                .collect::<Result<_, FixError>>()?,
1005        })
1006    }
1007}
1008
1009/// Position report (AP): one open position, or the news that there is none.
1010#[derive(Debug, Clone, PartialEq, Eq)]
1011pub struct PositionReport {
1012    /// Identifier of the request the report answers (710).
1013    pub pos_req_id: String,
1014    /// Identifier of the position (721).
1015    pub position_id: Option<PositionId>,
1016    /// Number of reports that answer the request (727).
1017    pub total_reports: u32,
1018    /// Code of the result; zero stands for a valid request, two for no position (728).
1019    pub result: u32,
1020    /// Symbol (55).
1021    pub symbol: Option<SymbolId>,
1022    /// Entry price of the position (730).
1023    pub settl_price: Option<Price>,
1024    /// Quantity bought (704).
1025    pub long_qty: Option<Volume>,
1026    /// Quantity sold (705).
1027    pub short_qty: Option<Volume>,
1028    /// Take profit as a price (1000).
1029    pub absolute_tp: Option<Price>,
1030    /// Stop loss as a price (1002).
1031    pub absolute_sl: Option<Price>,
1032    /// Tells whether the stop loss trails the price (1004).
1033    pub trailing_sl: Option<bool>,
1034    /// Code of the trigger method of the stop loss (1005).
1035    pub trigger_method_sl: Option<u32>,
1036    /// Tells whether the stop loss is guaranteed (1006).
1037    pub guaranteed_sl: Option<bool>,
1038}
1039
1040impl PositionReport {
1041    /// Type of the message (35).
1042    pub const MSG_TYPE: &'static str = "AP";
1043
1044    fn write(&self, out: &mut Vec<Field>) {
1045        put(out, TAG_POS_REQ_ID, &self.pos_req_id);
1046        put_optional(out, TAG_POSITION_ID, self.position_id.as_ref());
1047        put(out, TAG_TOTAL_REPORTS, &self.total_reports);
1048        put(out, TAG_POS_REQ_RESULT, &self.result);
1049        put_optional(out, TAG_SYMBOL, self.symbol.as_ref());
1050        put_optional(out, TAG_SETTL_PRICE, self.settl_price.as_ref());
1051        if self.long_qty.is_some() || self.short_qty.is_some() {
1052            put_count(out, TAG_NO_POSITIONS, 1);
1053        }
1054        put_optional(out, TAG_LONG_QTY, self.long_qty.as_ref());
1055        put_optional(out, TAG_SHORT_QTY, self.short_qty.as_ref());
1056        put_optional(out, TAG_ABSOLUTE_TP, self.absolute_tp.as_ref());
1057        put_optional(out, TAG_ABSOLUTE_SL, self.absolute_sl.as_ref());
1058        put_optional(out, TAG_TRAILING_SL, self.trailing_sl.as_ref());
1059        put_optional(out, TAG_TRIGGER_METHOD_SL, self.trigger_method_sl.as_ref());
1060        put_optional(out, TAG_GUARANTEED_SL, self.guaranteed_sl.as_ref());
1061    }
1062
1063    fn read(reader: &Reader<'_>) -> Result<Self, FixError> {
1064        Ok(Self {
1065            pos_req_id: reader.required(TAG_POS_REQ_ID)?,
1066            position_id: reader.optional(TAG_POSITION_ID)?,
1067            total_reports: reader.required(TAG_TOTAL_REPORTS)?,
1068            result: reader.required(TAG_POS_REQ_RESULT)?,
1069            symbol: reader.optional(TAG_SYMBOL)?,
1070            settl_price: reader.optional(TAG_SETTL_PRICE)?,
1071            long_qty: reader.optional(TAG_LONG_QTY)?,
1072            short_qty: reader.optional(TAG_SHORT_QTY)?,
1073            absolute_tp: reader.optional(TAG_ABSOLUTE_TP)?,
1074            absolute_sl: reader.optional(TAG_ABSOLUTE_SL)?,
1075            trailing_sl: reader.optional(TAG_TRAILING_SL)?,
1076            trigger_method_sl: reader.optional(TAG_TRIGGER_METHOD_SL)?,
1077            guaranteed_sl: reader.optional(TAG_GUARANTEED_SL)?,
1078        })
1079    }
1080}
1081
1082macro_rules! message_set {
1083    ($($name:ident: $doc:literal,)*) => {
1084        /// Any message the library sends or understands.
1085        #[derive(Debug, Clone, PartialEq, Eq)]
1086        #[non_exhaustive]
1087        pub enum Message {
1088            $(#[doc = $doc] $name($name),)*
1089            /// Execution report (8).
1090            ExecutionReport(Box<ExecutionReport>),
1091        }
1092
1093        impl Message {
1094            /// Returns the type of the message (35).
1095            #[must_use]
1096            pub const fn msg_type(&self) -> &'static str {
1097                match self {
1098                    $(Self::$name(_) => $name::MSG_TYPE,)*
1099                    Self::ExecutionReport(_) => ExecutionReport::MSG_TYPE,
1100                }
1101            }
1102
1103            /// Returns the fields of the body in the order of the wire.
1104            #[must_use]
1105            pub fn body(&self) -> Vec<Field> {
1106                let mut out = Vec::new();
1107                match self {
1108                    $(Self::$name(message) => message.write(&mut out),)*
1109                    Self::ExecutionReport(message) => message.write(&mut out),
1110                }
1111                out
1112            }
1113
1114            /// Parses the body of a message of the given type.
1115            ///
1116            /// # Errors
1117            ///
1118            /// Returns [`FixError::UnsupportedMessage`] for a type the library does not know,
1119            /// [`FixError::MissingField`] when a required field is absent and
1120            /// [`FixError::InvalidField`] when a value has the wrong form.
1121            pub fn parse(msg_type: &str, body: &[Field]) -> Result<Self, FixError> {
1122                $(if msg_type == $name::MSG_TYPE {
1123                    return $name::read(&Reader::new($name::MSG_TYPE, body)).map(Self::$name);
1124                })*
1125                if msg_type == ExecutionReport::MSG_TYPE {
1126                    return ExecutionReport::read(&Reader::new(ExecutionReport::MSG_TYPE, body))
1127                        .map(|report| Self::ExecutionReport(Box::new(report)));
1128                }
1129                Err(FixError::UnsupportedMessage(msg_type.to_owned()))
1130            }
1131        }
1132
1133        $(impl From<$name> for Message {
1134            fn from(message: $name) -> Self {
1135                Self::$name(message)
1136            }
1137        })*
1138    };
1139}
1140
1141message_set! {
1142    Heartbeat: "Heartbeat (0).",
1143    TestRequest: "Test request (1).",
1144    ResendRequest: "Resend request (2).",
1145    Reject: "Reject (3).",
1146    SequenceReset: "Sequence reset (4).",
1147    Logout: "Logout (5).",
1148    Logon: "Logon (A).",
1149    BusinessReject: "Business message reject (j).",
1150    MarketDataRequest: "Market data request (V).",
1151    MarketDataSnapshot: "Market data snapshot (W).",
1152    MarketDataIncremental: "Market data incremental refresh (X).",
1153    MarketDataReject: "Market data request reject (Y).",
1154    SecurityListRequest: "Security list request (x).",
1155    SecurityList: "Security list (y).",
1156    NewOrderSingle: "New order single (D).",
1157    OrderStatusRequest: "Order status request (H).",
1158    OrderMassStatusRequest: "Order mass status request (AF).",
1159    RequestForPositions: "Request for positions (AN).",
1160    PositionReport: "Position report (AP).",
1161    OrderCancelRequest: "Order cancel request (F).",
1162    OrderCancelReject: "Order cancel reject (9).",
1163    OrderCancelReplaceRequest: "Order cancel/replace request (G).",
1164}
1165
1166impl From<ExecutionReport> for Message {
1167    fn from(message: ExecutionReport) -> Self {
1168        Self::ExecutionReport(Box::new(message))
1169    }
1170}
1171
1172impl Message {
1173    /// Builds the frame of the message under the given header, whose message type is
1174    /// replaced by the one of the message.
1175    #[must_use]
1176    pub fn to_frame(&self, mut header: Header) -> Frame {
1177        self.msg_type().clone_into(&mut header.msg_type);
1178        Frame::new(header, self.body())
1179    }
1180
1181    /// Parses the message a frame carries.
1182    ///
1183    /// # Errors
1184    ///
1185    /// Returns the errors of [`Message::parse`].
1186    pub fn from_frame(frame: &Frame) -> Result<Self, FixError> {
1187        Self::parse(&frame.header.msg_type, &frame.body)
1188    }
1189
1190    /// Tells whether the message belongs to the session level: it is never sent again as
1191    /// it was, a sequence reset stands in for it.
1192    #[must_use]
1193    pub const fn is_administrative(&self) -> bool {
1194        matches!(
1195            self,
1196            Self::Heartbeat(_)
1197                | Self::TestRequest(_)
1198                | Self::ResendRequest(_)
1199                | Self::Reject(_)
1200                | Self::SequenceReset(_)
1201                | Self::Logout(_)
1202                | Self::Logon(_)
1203        )
1204    }
1205}
1206
1207#[cfg(test)]
1208#[path = "messages_tests.rs"]
1209mod tests;