1use 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 #[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 {
138 Buy => "1",
140 Sell => "2",
142 }
143}
144
145wire_enum! {
146 OrderKind {
148 Market => "1",
150 Limit => "2",
152 Stop => "3",
154 StopLimit => "4",
157 }
158}
159
160wire_enum! {
161 TimeInForce {
163 GoodTillCancel => "1",
165 ImmediateOrCancel => "3",
167 GoodTillDate => "6",
169 }
170}
171
172wire_enum! {
173 ExecType {
175 New => "0",
177 Canceled => "4",
179 Replaced => "5",
181 Rejected => "8",
183 Expired => "C",
185 Trade => "F",
187 OrderStatus => "I",
189 }
190}
191
192wire_enum! {
193 OrderStatus {
195 New => "0",
197 PartiallyFilled => "1",
199 Filled => "2",
201 Canceled => "4",
203 Replaced => "5",
205 Rejected => "8",
207 Expired => "C",
209 }
210}
211
212wire_enum! {
213 CancelRejectResponse {
215 Cancel => "1",
217 Replace => "2",
219 }
220}
221
222wire_enum! {
223 MarketDepth {
225 Full => "0",
227 Spot => "1",
229 }
230}
231
232wire_enum! {
233 BookSide {
235 Bid => "0",
237 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 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" {
381 opt test_req_id: String = 112,
383 }
384}
385
386flat! {
387 TestRequest, "1" {
389 req test_req_id: String = 112,
391 }
392}
393
394flat! {
395 ResendRequest, "2" {
397 req begin_seq_no: u64 = 7,
399 req end_seq_no: u64 = 16,
402 }
403}
404
405flat! {
406 Reject, "3" {
408 req ref_seq_num: u64 = 45,
410 opt text: String = 58,
412 opt ref_tag_id: u32 = 371,
414 opt ref_msg_type: String = 372,
416 opt reason: u32 = 373,
418 }
419}
420
421flat! {
422 SequenceReset, "4" {
424 opt gap_fill: bool = 123,
426 req new_seq_no: u64 = 36,
428 }
429}
430
431flat! {
432 Logout, "5" {
434 opt text: String = 58,
436 }
437}
438
439flat! {
440 Logon, "A" {
442 req encrypt_method: u32 = 98,
444 req heart_bt_int: u32 = 108,
446 opt reset_seq_num: bool = 141,
448 opt username: String = 553,
450 opt password: FixPassword = 554,
452 }
453}
454
455flat! {
456 BusinessReject, "j" {
458 opt ref_seq_num: u64 = 45,
460 opt ref_msg_type: String = 372,
462 opt ref_id: String = 379,
464 opt reason: u32 = 380,
466 opt text: String = 58,
468 }
469}
470
471flat! {
472 MarketDataReject, "Y" {
474 req md_req_id: String = 262,
476 opt reason: u32 = 281,
478 opt text: String = 58,
480 }
481}
482
483flat! {
484 SecurityListRequest, "x" {
486 req security_req_id: String = 320,
488 req request_type: u32 = 559,
490 opt symbol: SymbolId = 55,
492 }
493}
494
495flat! {
496 NewOrderSingle, "D" {
498 req cl_ord_id: String = 11,
500 req symbol: SymbolId = 55,
502 req side: Side = 54,
504 req transact_time: Timestamp = 60,
506 req order_qty: Volume = 38,
508 req ord_type: OrderKind = 40,
510 opt price: Price = 44,
512 opt stop_px: Price = 99,
514 opt time_in_force: TimeInForce = 59,
516 opt expire_time: Timestamp = 126,
518 opt position_id: PositionId = 721,
520 opt designation: String = 494,
522 }
523}
524
525flat! {
526 ExecutionReport, "8" {
528 lax order_id: OrderId = 37,
530 opt cl_ord_id: String = 11,
532 opt orig_cl_ord_id: String = 41,
534 opt tot_num_reports: u32 = 911,
536 req exec_type: ExecType = 150,
538 req ord_status: OrderStatus = 39,
540 opt symbol: SymbolId = 55,
542 opt side: Side = 54,
544 opt order_qty: Volume = 38,
546 opt ord_type: OrderKind = 40,
548 opt price: Price = 44,
550 opt stop_px: Price = 99,
552 opt time_in_force: TimeInForce = 59,
554 opt expire_time: Timestamp = 126,
556 opt last_qty: Volume = 32,
558 opt last_px: Price = 31,
560 opt leaves_qty: Volume = 151,
562 opt cum_qty: Volume = 14,
564 opt avg_px: Price = 6,
566 opt transact_time: Timestamp = 60,
568 opt text: String = 58,
570 opt ord_rej_reason: u32 = 103,
572 opt position_id: PositionId = 721,
574 opt designation: String = 494,
576 opt mass_status_req_id: String = 584,
578 opt absolute_tp: Price = 1000,
580 opt relative_tp: Decimal = 1001,
582 opt absolute_sl: Price = 1002,
584 opt relative_sl: Decimal = 1003,
586 opt trailing_sl: bool = 1004,
588 opt trigger_method_sl: u32 = 1005,
590 opt guaranteed_sl: bool = 1006,
592 }
593}
594
595flat! {
596 OrderStatusRequest, "H" {
598 req cl_ord_id: String = 11,
600 opt side: Side = 54,
602 }
603}
604
605flat! {
606 OrderMassStatusRequest, "AF" {
608 req mass_status_req_id: String = 584,
610 req request_type: u32 = 585,
612 opt issue_date: Timestamp = 225,
614 }
615}
616
617flat! {
618 RequestForPositions, "AN" {
620 req pos_req_id: String = 710,
622 opt position_id: PositionId = 721,
624 }
625}
626
627flat! {
628 OrderCancelRequest, "F" {
630 req orig_cl_ord_id: String = 41,
632 opt order_id: OrderId = 37,
634 req cl_ord_id: String = 11,
636 }
637}
638
639flat! {
640 OrderCancelReject, "9" {
642 lax order_id: OrderId = 37,
644 req cl_ord_id: String = 11,
646 opt orig_cl_ord_id: String = 41,
648 req ord_status: OrderStatus = 39,
650 req response_to: CancelRejectResponse = 434,
652 opt text: String = 58,
654 }
655}
656
657flat! {
658 OrderCancelReplaceRequest, "G" {
660 req orig_cl_ord_id: String = 41,
662 opt order_id: OrderId = 37,
664 req cl_ord_id: String = 11,
666 req order_qty: Volume = 38,
668 opt price: Price = 44,
670 opt stop_px: Price = 99,
672 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#[derive(Debug, Clone, PartialEq, Eq)]
718pub struct MarketDataRequest {
719 pub md_req_id: String,
721 pub subscribe: bool,
723 pub depth: MarketDepth,
725 pub symbols: Vec<SymbolId>,
727 pub sides: Vec<BookSide>,
729}
730
731impl MarketDataRequest {
732 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#[derive(Debug, Clone, PartialEq, Eq)]
781pub struct SnapshotEntry {
782 pub side: BookSide,
784 pub price: Price,
786 pub size: Option<Volume>,
788 pub id: Option<String>,
790}
791
792#[derive(Debug, Clone, PartialEq, Eq)]
794pub struct MarketDataSnapshot {
795 pub md_req_id: Option<String>,
797 pub symbol: SymbolId,
799 pub entries: Vec<SnapshotEntry>,
801}
802
803impl MarketDataSnapshot {
804 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#[derive(Debug, Clone, PartialEq, Eq)]
848pub enum BookUpdate {
849 New {
851 side: BookSide,
853 id: String,
855 symbol: SymbolId,
857 price: Price,
859 size: Option<Volume>,
861 },
862 Delete {
864 id: String,
866 symbol: SymbolId,
868 },
869}
870
871#[derive(Debug, Clone, PartialEq, Eq)]
873pub struct MarketDataIncremental {
874 pub md_req_id: Option<String>,
876 pub entries: Vec<BookUpdate>,
878}
879
880impl MarketDataIncremental {
881 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#[derive(Debug, Clone, PartialEq, Eq)]
948pub struct SecurityEntry {
949 pub symbol: SymbolId,
951 pub name: Option<String>,
953 pub digits: Option<u32>,
955}
956
957#[derive(Debug, Clone, PartialEq, Eq)]
959pub struct SecurityList {
960 pub security_req_id: String,
962 pub security_response_id: String,
964 pub result: u32,
966 pub symbols: Vec<SecurityEntry>,
968}
969
970impl SecurityList {
971 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#[derive(Debug, Clone, PartialEq, Eq)]
1011pub struct PositionReport {
1012 pub pos_req_id: String,
1014 pub position_id: Option<PositionId>,
1016 pub total_reports: u32,
1018 pub result: u32,
1020 pub symbol: Option<SymbolId>,
1022 pub settl_price: Option<Price>,
1024 pub long_qty: Option<Volume>,
1026 pub short_qty: Option<Volume>,
1028 pub absolute_tp: Option<Price>,
1030 pub absolute_sl: Option<Price>,
1032 pub trailing_sl: Option<bool>,
1034 pub trigger_method_sl: Option<u32>,
1036 pub guaranteed_sl: Option<bool>,
1038}
1039
1040impl PositionReport {
1041 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 #[derive(Debug, Clone, PartialEq, Eq)]
1086 #[non_exhaustive]
1087 pub enum Message {
1088 $(#[doc = $doc] $name($name),)*
1089 ExecutionReport(Box<ExecutionReport>),
1091 }
1092
1093 impl Message {
1094 #[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 #[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 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 #[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 pub fn from_frame(frame: &Frame) -> Result<Self, FixError> {
1187 Self::parse(&frame.header.msg_type, &frame.body)
1188 }
1189
1190 #[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;