refix-dictionary 0.4.0

FIX dictionary model and frontends for the ReFIX engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use refix_message::Tag;
use std::borrow::Cow;
use std::fmt;

/// The fields, messages, components, header and trailer of one FIX version
/// or venue dialect, as authored.
///
/// A spec is plain data and makes no consistency guarantees. It is what
/// frontends parse into and what dialect authors construct by hand.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Spec {
    pub version: Version,
    /// The members every message starts with, in source order.
    pub header: Vec<Member>,
    pub messages: Vec<Message>,
    /// The members every message ends with, in source order.
    pub trailer: Vec<Member>,
    pub fields: Vec<Field>,
    pub components: Vec<Component>,
}

/// The definition of a FIX message type.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Message {
    /// The name of the message type.
    pub name: String,
    /// The wire value of `MsgType(35)`, verbatim, e.g. `"D"`.
    pub msg_type: String,
    /// The message's members in source order.
    pub members: Vec<Member>,
    /// The category of this message.
    pub category: Category,
}

/// A field definition, as listed in the dictionary's fields section.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Field {
    pub name: String,
    pub tag: Tag,
    pub data_type: DataType,
    /// For a data field, the tag of the field that gives its length.
    pub length_tag: Option<Tag>,
    pub values: Vec<EnumValue>,
}

/// A component definition, as listed in the dictionary's components section.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Component {
    /// The name of the component.
    pub name: String,
    /// The component's members in source order.
    pub members: Vec<Member>,
}

/// A member of a message, component or group instance.
///
/// This can be a field reference, a component reference or a repeating group.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Member {
    Field(FieldRef),
    Component(ComponentRef),
    Group(Group),
}

/// A field as used by one message or component (Orchestra's `fieldRef`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FieldRef {
    /// Tag of the referenced [`Field`] definition.
    pub tag: Tag,
    pub is_required: bool,
}

/// A component as used by one message or component.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ComponentRef {
    /// Name of the referenced [`Component`] definition.
    pub name: String,
    pub is_required: bool,
}

/// A repeating group, declared inline in a message, component or group
/// instance.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Group {
    /// Tag of the group's NumInGroup count field.
    pub count_tag: Tag,
    pub is_required: bool,
    /// The members of each instance, in source order.
    pub members: Vec<Member>,
}

/// The message, component, group instance, header or trailer a member
/// appears in.
///
/// Diagnostics use this to name the place a problem was found.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum MemberContext {
    Message(String),
    Component(String),
    Header,
    Trailer,
    /// A group's instances, named after the group's count field.
    Group {
        name: String,
        parent: Box<MemberContext>,
    },
}

impl MemberContext {
    /// The context of a group's instances, nested in this context.
    pub fn group(&self, name: &str) -> MemberContext {
        MemberContext::Group {
            name: name.to_owned(),
            parent: Box::new(self.clone()),
        }
    }
}

impl fmt::Display for MemberContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Message(name) => write!(f, "message '{name}'"),
            Self::Component(name) => write!(f, "component '{name}'"),
            Self::Header => write!(f, "the header"),
            Self::Trailer => write!(f, "the trailer"),
            Self::Group { name, parent } => write!(f, "group '{name}' in {parent}"),
        }
    }
}

/// An enum variant's value.
///
/// This models the `<value enum="..." description="..." />` elements in a field definition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EnumValue {
    pub value: String,
    pub description: String,
}

/// The FIX data type of a field, as declared in the dictionary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DataType {
    String,
    Int,
    Length,
    NumInGroup,
    SeqNum,
    TagNum,
    DayOfMonth,
    Float,
    Qty,
    Price,
    PriceOffset,
    Amt,
    Percentage,
    Char,
    Boolean,
    MultipleCharValue,
    /// Also FIX 4.4's `MultipleValueString`.
    MultipleStringValue,
    Currency,
    Exchange,
    Country,
    Language,
    Xid,
    XidRef,
    /// Also FIX 4.0 and 4.1's `Time`.
    UtcTimestamp,
    UtcTimeOnly,
    /// Also FIX 4.2 and 4.3's `UtcDate`.
    UtcDateOnly,
    /// Also FIX 4.0 and 4.1's `Date`.
    LocalMktDate,
    LocalMktTime,
    MonthYear,
    TzTimestamp,
    TzTimeOnly,
    Data,
    XmlData,
    /// A type outside the standard, such as a venue's own.
    Other(String),
}

/// The type's name in upper case, as dictionaries declare it, or a type outside
/// the standard as given.
impl fmt::Display for DataType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::String => "STRING",
            Self::Int => "INT",
            Self::Length => "LENGTH",
            Self::NumInGroup => "NUMINGROUP",
            Self::SeqNum => "SEQNUM",
            Self::TagNum => "TAGNUM",
            Self::DayOfMonth => "DAYOFMONTH",
            Self::Float => "FLOAT",
            Self::Qty => "QTY",
            Self::Price => "PRICE",
            Self::PriceOffset => "PRICEOFFSET",
            Self::Amt => "AMT",
            Self::Percentage => "PERCENTAGE",
            Self::Char => "CHAR",
            Self::Boolean => "BOOLEAN",
            Self::MultipleCharValue => "MULTIPLECHARVALUE",
            Self::MultipleStringValue => "MULTIPLESTRINGVALUE",
            Self::Currency => "CURRENCY",
            Self::Exchange => "EXCHANGE",
            Self::Country => "COUNTRY",
            Self::Language => "LANGUAGE",
            Self::Xid => "XID",
            Self::XidRef => "XIDREF",
            Self::UtcTimestamp => "UTCTIMESTAMP",
            Self::UtcTimeOnly => "UTCTIMEONLY",
            Self::UtcDateOnly => "UTCDATEONLY",
            Self::LocalMktDate => "LOCALMKTDATE",
            Self::LocalMktTime => "LOCALMKTTIME",
            Self::MonthYear => "MONTHYEAR",
            Self::TzTimestamp => "TZTIMESTAMP",
            Self::TzTimeOnly => "TZTIMEONLY",
            Self::Data => "DATA",
            Self::XmlData => "XMLDATA",
            Self::Other(name) => name,
        };
        f.write_str(name)
    }
}

impl DataType {
    /// Whether the type is `Int` or one of its subtypes.
    pub fn is_int_based(&self) -> bool {
        matches!(
            self,
            Self::Int
                | Self::Length
                | Self::NumInGroup
                | Self::SeqNum
                | Self::TagNum
                | Self::DayOfMonth
        )
    }

    /// Whether the type is `Float` or one of its subtypes.
    pub fn is_float_based(&self) -> bool {
        matches!(
            self,
            Self::Float
                | Self::Qty
                | Self::Price
                | Self::PriceOffset
                | Self::Amt
                | Self::Percentage
        )
    }

    /// Whether the type holds space-delimited values, as `ExecInst(18)` does.
    pub fn is_multiple_value(&self) -> bool {
        matches!(self, Self::MultipleCharValue | Self::MultipleStringValue)
    }

    /// Whether a field of this type takes its length from another field, as
    /// `RawData(96)` does.
    pub(crate) fn has_length_field(&self) -> bool {
        matches!(self, Self::Data | Self::XmlData)
    }

    /// A code in the form every code for its value shares.
    ///
    /// An int-based type reads codes as numbers, so `01` and `1` agree.
    pub(crate) fn canonical_code<'a>(&self, code: &'a str) -> Cow<'a, str> {
        match code.parse::<i64>() {
            Ok(number) if self.is_int_based() => Cow::Owned(number.to_string()),
            _ => Cow::Borrowed(code),
        }
    }
}

/// The FIX version a dictionary describes, e.g. FIX 4.4 or FIXT 1.1.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Version {
    pub protocol: Protocol,
    pub major: u8,
    pub minor: u8,
    pub service_pack: u8,
}

/// The protocol family a dictionary belongs to.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Protocol {
    /// Classic FIX (4.x and earlier), session and application layers in
    /// one dictionary.
    Fix,
    /// The FIXT transport (FIX 5.x onwards), where the session layer is
    /// versioned separately from application semantics.
    Fixt,
}

/// Whether a message belongs to the session layer or the application layer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Category {
    /// Session-level machinery: Logon, Heartbeat, Reject, etc.
    Admin,
    /// Business messages: orders, executions, market data.
    App,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_int_family_is_int_based() {
        for data_type in [
            DataType::Int,
            DataType::Length,
            DataType::NumInGroup,
            DataType::SeqNum,
            DataType::TagNum,
            DataType::DayOfMonth,
        ] {
            assert!(data_type.is_int_based(), "{data_type:?}");
        }
    }

    #[test]
    fn other_types_are_not_int_based() {
        for data_type in [
            DataType::String,
            DataType::Char,
            DataType::MultipleStringValue,
            DataType::Price,
            DataType::Other("CUSTOM".to_owned()),
        ] {
            assert!(!data_type.is_int_based(), "{data_type:?}");
        }
    }

    #[test]
    fn the_float_family_is_float_based() {
        for data_type in [
            DataType::Float,
            DataType::Qty,
            DataType::Price,
            DataType::PriceOffset,
            DataType::Amt,
            DataType::Percentage,
        ] {
            assert!(data_type.is_float_based(), "{data_type:?}");
        }
    }

    #[test]
    fn other_types_are_not_float_based() {
        for data_type in [
            DataType::Int,
            DataType::String,
            DataType::UtcTimestamp,
            DataType::Other("CUSTOM".to_owned()),
        ] {
            assert!(!data_type.is_float_based(), "{data_type:?}");
        }
    }

    #[test]
    fn the_multiple_value_types_hold_multiple_values() {
        assert!(DataType::MultipleCharValue.is_multiple_value());
        assert!(DataType::MultipleStringValue.is_multiple_value());
        assert!(!DataType::String.is_multiple_value());
        assert!(!DataType::Char.is_multiple_value());
    }

    #[test]
    fn int_codes_are_canonical_as_numbers() {
        assert_eq!(DataType::Int.canonical_code("01"), "1");
        assert_eq!(DataType::Int.canonical_code("-007"), "-7");
        assert_eq!(DataType::Char.canonical_code("01"), "01");
    }

    #[test]
    fn a_header_group_names_the_header() {
        assert_eq!(
            MemberContext::Header.group("NoHops").to_string(),
            "group 'NoHops' in the header"
        );
        assert_eq!(MemberContext::Trailer.to_string(), "the trailer");
    }

    #[test]
    fn a_nested_group_context_names_its_whole_path() {
        let context = MemberContext::Group {
            name: "NoPartySubIDs".to_owned(),
            parent: Box::new(MemberContext::Group {
                name: "NoPartyIDs".to_owned(),
                parent: Box::new(MemberContext::Component("Parties".to_owned())),
            }),
        };

        assert_eq!(
            context.to_string(),
            "group 'NoPartySubIDs' in group 'NoPartyIDs' in component 'Parties'"
        );

        assert_eq!(
            context.to_string(),
            "group 'NoPartySubIDs' in group 'NoPartyIDs' in component 'Parties'"
        );
    }
}