use std::str::FromStr;
use rust_decimal::Decimal;
use crate::common::config::FixPassword;
use crate::common::decimals::{Price, Volume};
use crate::common::errors::FixError;
use crate::common::ids::{OrderId, PositionId, SymbolId};
use crate::common::time::Timestamp;
use crate::fix::codec::{Field, Frame, Header, format_time, parse_time};
trait Wire: Sized {
fn to_wire(&self) -> String;
fn from_wire(text: &str) -> Option<Self>;
}
impl Wire for String {
fn to_wire(&self) -> String {
self.clone()
}
fn from_wire(text: &str) -> Option<Self> {
Some(text.to_owned())
}
}
impl Wire for bool {
fn to_wire(&self) -> String {
if *self { "Y" } else { "N" }.to_owned()
}
fn from_wire(text: &str) -> Option<Self> {
match text {
"Y" => Some(true),
"N" => Some(false),
_ => None,
}
}
}
impl Wire for Timestamp {
fn to_wire(&self) -> String {
format_time(*self, self.as_millis() % 1_000 != 0)
}
fn from_wire(text: &str) -> Option<Self> {
parse_time(text)
}
}
impl Wire for FixPassword {
fn to_wire(&self) -> String {
self.expose().to_owned()
}
fn from_wire(text: &str) -> Option<Self> {
Self::new(text).ok()
}
}
macro_rules! wire_from_str {
($($ty:ty),*) => {
$(impl Wire for $ty {
fn to_wire(&self) -> String {
self.to_string()
}
fn from_wire(text: &str) -> Option<Self> {
<$ty>::from_str(text).ok()
}
})*
};
}
wire_from_str!(
u32, u64, Decimal, Price, Volume, SymbolId, OrderId, PositionId
);
macro_rules! wire_enum {
($(#[$doc:meta])* $name:ident { $($(#[$vdoc:meta])* $variant:ident => $wire:literal,)* }) => {
$(#[$doc])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum $name {
$($(#[$vdoc])* $variant,)*
}
impl $name {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
$(Self::$variant => $wire,)*
}
}
}
impl Wire for $name {
fn to_wire(&self) -> String {
self.as_str().to_owned()
}
fn from_wire(text: &str) -> Option<Self> {
match text {
$($wire => Some(Self::$variant),)*
_ => None,
}
}
}
};
}
wire_enum! {
Side {
Buy => "1",
Sell => "2",
}
}
wire_enum! {
OrderKind {
Market => "1",
Limit => "2",
Stop => "3",
StopLimit => "4",
}
}
wire_enum! {
TimeInForce {
GoodTillCancel => "1",
ImmediateOrCancel => "3",
GoodTillDate => "6",
}
}
wire_enum! {
ExecType {
New => "0",
Canceled => "4",
Replaced => "5",
Rejected => "8",
Expired => "C",
Trade => "F",
OrderStatus => "I",
}
}
wire_enum! {
OrderStatus {
New => "0",
PartiallyFilled => "1",
Filled => "2",
Canceled => "4",
Replaced => "5",
Rejected => "8",
Expired => "C",
}
}
wire_enum! {
CancelRejectResponse {
Cancel => "1",
Replace => "2",
}
}
wire_enum! {
MarketDepth {
Full => "0",
Spot => "1",
}
}
wire_enum! {
BookSide {
Bid => "0",
Offer => "1",
}
}
struct Reader<'a> {
kind: &'static str,
fields: &'a [Field],
}
impl<'a> Reader<'a> {
const fn new(kind: &'static str, fields: &'a [Field]) -> Self {
Self { kind, fields }
}
fn missing(&self, tag: u32) -> FixError {
FixError::MissingField {
msg_type: self.kind.to_owned(),
tag,
}
}
fn invalid(&self, tag: u32) -> FixError {
FixError::InvalidField {
msg_type: self.kind.to_owned(),
tag,
}
}
fn text(&self, tag: u32) -> Option<&'a str> {
self.fields
.iter()
.find(|field| field.tag == tag)
.map(|field| field.value.as_str())
}
fn optional<T: Wire>(&self, tag: u32) -> Result<Option<T>, FixError> {
self.text(tag)
.map(|text| T::from_wire(text).ok_or_else(|| self.invalid(tag)))
.transpose()
}
fn required<T: Wire>(&self, tag: u32) -> Result<T, FixError> {
self.optional(tag)?.ok_or_else(|| self.missing(tag))
}
fn lax<T: Wire>(&self, tag: u32) -> Option<T> {
self.text(tag).and_then(T::from_wire)
}
fn group(&self, count_tag: u32, members: &[u32]) -> Result<Vec<Self>, FixError> {
let Some(at) = self.fields.iter().position(|field| field.tag == count_tag) else {
return Ok(Vec::new());
};
let count: u32 = self.required(count_tag)?;
let rest = self.fields.get(at.saturating_add(1)..).unwrap_or(&[]);
let length = rest
.iter()
.position(|field| !members.contains(&field.tag))
.unwrap_or(rest.len());
let inside = rest.get(..length).unwrap_or(rest);
let delimiter = members.first().copied().unwrap_or(0);
let mut entries = Vec::new();
let mut start = 0_usize;
for (index, field) in inside.iter().enumerate() {
if field.tag == delimiter && index > 0 {
entries.push(Self::new(
self.kind,
inside.get(start..index).unwrap_or(&[]),
));
start = index;
}
}
match inside.first() {
Some(first) if first.tag == delimiter => {
entries.push(Self::new(self.kind, inside.get(start..).unwrap_or(&[])));
}
Some(_) => return Err(self.invalid(count_tag)),
None => {}
}
if u32::try_from(entries.len()).ok() == Some(count) {
Ok(entries)
} else {
Err(self.invalid(count_tag))
}
}
}
fn put<T: Wire>(out: &mut Vec<Field>, tag: u32, value: &T) {
out.push(Field::new(tag, value.to_wire()));
}
fn put_optional<T: Wire>(out: &mut Vec<Field>, tag: u32, value: Option<&T>) {
if let Some(value) = value {
put(out, tag, value);
}
}
fn put_count(out: &mut Vec<Field>, tag: u32, count: usize) {
out.push(Field::new(tag, count.to_string()));
}
macro_rules! flat {
(
$(#[$doc:meta])* $name:ident, $kind:literal {
$($(#[$fdoc:meta])* $mode:ident $field:ident: $ty:ty = $tag:literal,)*
}
) => {
$(#[$doc])*
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct $name {
$($(#[$fdoc])* pub $field: flat!(@ty $mode $ty),)*
}
impl $name {
pub const MSG_TYPE: &'static str = $kind;
fn write(&self, out: &mut Vec<Field>) {
$(flat!(@put $mode out, $tag, self.$field);)*
}
fn read(reader: &Reader<'_>) -> Result<Self, FixError> {
Ok(Self {
$($field: flat!(@get $mode reader, $tag),)*
})
}
}
};
(@ty req $ty:ty) => { $ty };
(@ty opt $ty:ty) => { Option<$ty> };
(@ty lax $ty:ty) => { Option<$ty> };
(@put req $out:ident, $tag:literal, $value:expr) => { put($out, $tag, &$value) };
(@put opt $out:ident, $tag:literal, $value:expr) => { put_optional($out, $tag, $value.as_ref()) };
(@put lax $out:ident, $tag:literal, $value:expr) => { put_optional($out, $tag, $value.as_ref()) };
(@get req $reader:ident, $tag:literal) => { $reader.required($tag)? };
(@get opt $reader:ident, $tag:literal) => { $reader.optional($tag)? };
(@get lax $reader:ident, $tag:literal) => { $reader.lax($tag) };
}
flat! {
Heartbeat, "0" {
opt test_req_id: String = 112,
}
}
flat! {
TestRequest, "1" {
req test_req_id: String = 112,
}
}
flat! {
ResendRequest, "2" {
req begin_seq_no: u64 = 7,
req end_seq_no: u64 = 16,
}
}
flat! {
Reject, "3" {
req ref_seq_num: u64 = 45,
opt text: String = 58,
opt ref_tag_id: u32 = 371,
opt ref_msg_type: String = 372,
opt reason: u32 = 373,
}
}
flat! {
SequenceReset, "4" {
opt gap_fill: bool = 123,
req new_seq_no: u64 = 36,
}
}
flat! {
Logout, "5" {
opt text: String = 58,
}
}
flat! {
Logon, "A" {
req encrypt_method: u32 = 98,
req heart_bt_int: u32 = 108,
opt reset_seq_num: bool = 141,
opt username: String = 553,
opt password: FixPassword = 554,
}
}
flat! {
BusinessReject, "j" {
opt ref_seq_num: u64 = 45,
opt ref_msg_type: String = 372,
opt ref_id: String = 379,
opt reason: u32 = 380,
opt text: String = 58,
}
}
flat! {
MarketDataReject, "Y" {
req md_req_id: String = 262,
opt reason: u32 = 281,
opt text: String = 58,
}
}
flat! {
SecurityListRequest, "x" {
req security_req_id: String = 320,
req request_type: u32 = 559,
opt symbol: SymbolId = 55,
}
}
flat! {
NewOrderSingle, "D" {
req cl_ord_id: String = 11,
req symbol: SymbolId = 55,
req side: Side = 54,
req transact_time: Timestamp = 60,
req order_qty: Volume = 38,
req ord_type: OrderKind = 40,
opt price: Price = 44,
opt stop_px: Price = 99,
opt time_in_force: TimeInForce = 59,
opt expire_time: Timestamp = 126,
opt position_id: PositionId = 721,
opt designation: String = 494,
}
}
flat! {
ExecutionReport, "8" {
lax order_id: OrderId = 37,
opt cl_ord_id: String = 11,
opt orig_cl_ord_id: String = 41,
opt tot_num_reports: u32 = 911,
req exec_type: ExecType = 150,
req ord_status: OrderStatus = 39,
opt symbol: SymbolId = 55,
opt side: Side = 54,
opt order_qty: Volume = 38,
opt ord_type: OrderKind = 40,
opt price: Price = 44,
opt stop_px: Price = 99,
opt time_in_force: TimeInForce = 59,
opt expire_time: Timestamp = 126,
opt last_qty: Volume = 32,
opt last_px: Price = 31,
opt leaves_qty: Volume = 151,
opt cum_qty: Volume = 14,
opt avg_px: Price = 6,
opt transact_time: Timestamp = 60,
opt text: String = 58,
opt ord_rej_reason: u32 = 103,
opt position_id: PositionId = 721,
opt designation: String = 494,
opt mass_status_req_id: String = 584,
opt absolute_tp: Price = 1000,
opt relative_tp: Decimal = 1001,
opt absolute_sl: Price = 1002,
opt relative_sl: Decimal = 1003,
opt trailing_sl: bool = 1004,
opt trigger_method_sl: u32 = 1005,
opt guaranteed_sl: bool = 1006,
}
}
flat! {
OrderStatusRequest, "H" {
req cl_ord_id: String = 11,
opt side: Side = 54,
}
}
flat! {
OrderMassStatusRequest, "AF" {
req mass_status_req_id: String = 584,
req request_type: u32 = 585,
opt issue_date: Timestamp = 225,
}
}
flat! {
RequestForPositions, "AN" {
req pos_req_id: String = 710,
opt position_id: PositionId = 721,
}
}
flat! {
OrderCancelRequest, "F" {
req orig_cl_ord_id: String = 41,
opt order_id: OrderId = 37,
req cl_ord_id: String = 11,
}
}
flat! {
OrderCancelReject, "9" {
lax order_id: OrderId = 37,
req cl_ord_id: String = 11,
opt orig_cl_ord_id: String = 41,
req ord_status: OrderStatus = 39,
req response_to: CancelRejectResponse = 434,
opt text: String = 58,
}
}
flat! {
OrderCancelReplaceRequest, "G" {
req orig_cl_ord_id: String = 41,
opt order_id: OrderId = 37,
req cl_ord_id: String = 11,
req order_qty: Volume = 38,
opt price: Price = 44,
opt stop_px: Price = 99,
opt expire_time: Timestamp = 126,
}
}
const TAG_SYMBOL: u32 = 55;
const TAG_LONG_QTY: u32 = 704;
const TAG_SHORT_QTY: u32 = 705;
const TAG_NO_RELATED_SYM: u32 = 146;
const TAG_MD_REQ_ID: u32 = 262;
const TAG_SUBSCRIPTION: u32 = 263;
const TAG_MARKET_DEPTH: u32 = 264;
const TAG_UPDATE_TYPE: u32 = 265;
const TAG_NO_ENTRY_TYPES: u32 = 267;
const TAG_NO_ENTRIES: u32 = 268;
const TAG_ENTRY_TYPE: u32 = 269;
const TAG_ENTRY_PX: u32 = 270;
const TAG_ENTRY_SIZE: u32 = 271;
const TAG_ENTRY_ID: u32 = 278;
const TAG_UPDATE_ACTION: u32 = 279;
const TAG_QUOTE_ENTRY_ID: u32 = 299;
const TAG_SECURITY_REQ_ID: u32 = 320;
const TAG_SECURITY_RESPONSE_ID: u32 = 322;
const TAG_SECURITY_RESULT: u32 = 560;
const TAG_NO_POSITIONS: u32 = 702;
const TAG_POS_REQ_ID: u32 = 710;
const TAG_POSITION_ID: u32 = 721;
const TAG_TOTAL_REPORTS: u32 = 727;
const TAG_POS_REQ_RESULT: u32 = 728;
const TAG_SETTL_PRICE: u32 = 730;
const TAG_SYMBOL_NAME: u32 = 1007;
const TAG_SYMBOL_DIGITS: u32 = 1008;
const TAG_ABSOLUTE_TP: u32 = 1000;
const TAG_ABSOLUTE_SL: u32 = 1002;
const TAG_TRAILING_SL: u32 = 1004;
const TAG_TRIGGER_METHOD_SL: u32 = 1005;
const TAG_GUARANTEED_SL: u32 = 1006;
const SUBSCRIBE: &str = "1";
const UNSUBSCRIBE: &str = "2";
const INCREMENTAL_REFRESH: &str = "1";
const ACTION_NEW: &str = "0";
const ACTION_DELETE: &str = "2";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarketDataRequest {
pub md_req_id: String,
pub subscribe: bool,
pub depth: MarketDepth,
pub symbols: Vec<SymbolId>,
pub sides: Vec<BookSide>,
}
impl MarketDataRequest {
pub const MSG_TYPE: &'static str = "V";
fn write(&self, out: &mut Vec<Field>) {
put(out, TAG_MD_REQ_ID, &self.md_req_id);
let subscription = if self.subscribe {
SUBSCRIBE
} else {
UNSUBSCRIBE
};
out.push(Field::new(TAG_SUBSCRIPTION, subscription));
put(out, TAG_MARKET_DEPTH, &self.depth);
out.push(Field::new(TAG_UPDATE_TYPE, INCREMENTAL_REFRESH));
put_count(out, TAG_NO_RELATED_SYM, self.symbols.len());
for symbol in &self.symbols {
put(out, TAG_SYMBOL, symbol);
}
put_count(out, TAG_NO_ENTRY_TYPES, self.sides.len());
for side in &self.sides {
put(out, TAG_ENTRY_TYPE, side);
}
}
fn read(reader: &Reader<'_>) -> Result<Self, FixError> {
let subscribe = match reader.required::<String>(TAG_SUBSCRIPTION)?.as_str() {
SUBSCRIBE => true,
UNSUBSCRIBE => false,
_ => return Err(reader.invalid(TAG_SUBSCRIPTION)),
};
Ok(Self {
md_req_id: reader.required(TAG_MD_REQ_ID)?,
subscribe,
depth: reader.required(TAG_MARKET_DEPTH)?,
symbols: reader
.group(TAG_NO_RELATED_SYM, &[TAG_SYMBOL])?
.iter()
.map(|entry| entry.required(TAG_SYMBOL))
.collect::<Result<_, _>>()?,
sides: reader
.group(TAG_NO_ENTRY_TYPES, &[TAG_ENTRY_TYPE])?
.iter()
.map(|entry| entry.required(TAG_ENTRY_TYPE))
.collect::<Result<_, _>>()?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SnapshotEntry {
pub side: BookSide,
pub price: Price,
pub size: Option<Volume>,
pub id: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarketDataSnapshot {
pub md_req_id: Option<String>,
pub symbol: SymbolId,
pub entries: Vec<SnapshotEntry>,
}
impl MarketDataSnapshot {
pub const MSG_TYPE: &'static str = "W";
fn write(&self, out: &mut Vec<Field>) {
put_optional(out, TAG_MD_REQ_ID, self.md_req_id.as_ref());
put(out, TAG_SYMBOL, &self.symbol);
put_count(out, TAG_NO_ENTRIES, self.entries.len());
for entry in &self.entries {
put(out, TAG_ENTRY_TYPE, &entry.side);
put(out, TAG_ENTRY_PX, &entry.price);
put_optional(out, TAG_ENTRY_SIZE, entry.size.as_ref());
put_optional(out, TAG_ENTRY_ID, entry.id.as_ref());
}
}
fn read(reader: &Reader<'_>) -> Result<Self, FixError> {
let members = [
TAG_ENTRY_TYPE,
TAG_QUOTE_ENTRY_ID,
TAG_ENTRY_PX,
TAG_ENTRY_SIZE,
TAG_ENTRY_ID,
];
Ok(Self {
md_req_id: reader.optional(TAG_MD_REQ_ID)?,
symbol: reader.required(TAG_SYMBOL)?,
entries: reader
.group(TAG_NO_ENTRIES, &members)?
.iter()
.map(|entry| {
Ok(SnapshotEntry {
side: entry.required(TAG_ENTRY_TYPE)?,
price: entry.required(TAG_ENTRY_PX)?,
size: entry.optional(TAG_ENTRY_SIZE)?,
id: entry.optional(TAG_ENTRY_ID)?,
})
})
.collect::<Result<_, FixError>>()?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BookUpdate {
New {
side: BookSide,
id: String,
symbol: SymbolId,
price: Price,
size: Option<Volume>,
},
Delete {
id: String,
symbol: SymbolId,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarketDataIncremental {
pub md_req_id: Option<String>,
pub entries: Vec<BookUpdate>,
}
impl MarketDataIncremental {
pub const MSG_TYPE: &'static str = "X";
fn write(&self, out: &mut Vec<Field>) {
put_optional(out, TAG_MD_REQ_ID, self.md_req_id.as_ref());
put_count(out, TAG_NO_ENTRIES, self.entries.len());
for entry in &self.entries {
match entry {
BookUpdate::New {
side,
id,
symbol,
price,
size,
} => {
out.push(Field::new(TAG_UPDATE_ACTION, ACTION_NEW));
put(out, TAG_ENTRY_TYPE, side);
put(out, TAG_ENTRY_ID, id);
put(out, TAG_SYMBOL, symbol);
put(out, TAG_ENTRY_PX, price);
put_optional(out, TAG_ENTRY_SIZE, size.as_ref());
}
BookUpdate::Delete { id, symbol } => {
out.push(Field::new(TAG_UPDATE_ACTION, ACTION_DELETE));
put(out, TAG_ENTRY_ID, id);
put(out, TAG_SYMBOL, symbol);
}
}
}
}
fn read(reader: &Reader<'_>) -> Result<Self, FixError> {
let members = [
TAG_UPDATE_ACTION,
TAG_ENTRY_TYPE,
TAG_ENTRY_ID,
TAG_SYMBOL,
TAG_ENTRY_PX,
TAG_ENTRY_SIZE,
];
Ok(Self {
md_req_id: reader.optional(TAG_MD_REQ_ID)?,
entries: reader
.group(TAG_NO_ENTRIES, &members)?
.iter()
.map(|entry| {
let id = entry.required(TAG_ENTRY_ID)?;
let symbol = entry.required(TAG_SYMBOL)?;
match entry.required::<String>(TAG_UPDATE_ACTION)?.as_str() {
ACTION_NEW => Ok(BookUpdate::New {
side: entry.required(TAG_ENTRY_TYPE)?,
id,
symbol,
price: entry.required(TAG_ENTRY_PX)?,
size: entry.optional(TAG_ENTRY_SIZE)?,
}),
ACTION_DELETE => Ok(BookUpdate::Delete { id, symbol }),
_ => Err(entry.invalid(TAG_UPDATE_ACTION)),
}
})
.collect::<Result<_, FixError>>()?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecurityEntry {
pub symbol: SymbolId,
pub name: Option<String>,
pub digits: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecurityList {
pub security_req_id: String,
pub security_response_id: String,
pub result: u32,
pub symbols: Vec<SecurityEntry>,
}
impl SecurityList {
pub const MSG_TYPE: &'static str = "y";
fn write(&self, out: &mut Vec<Field>) {
put(out, TAG_SECURITY_REQ_ID, &self.security_req_id);
put(out, TAG_SECURITY_RESPONSE_ID, &self.security_response_id);
put(out, TAG_SECURITY_RESULT, &self.result);
if !self.symbols.is_empty() {
put_count(out, TAG_NO_RELATED_SYM, self.symbols.len());
}
for entry in &self.symbols {
put(out, TAG_SYMBOL, &entry.symbol);
put_optional(out, TAG_SYMBOL_NAME, entry.name.as_ref());
put_optional(out, TAG_SYMBOL_DIGITS, entry.digits.as_ref());
}
}
fn read(reader: &Reader<'_>) -> Result<Self, FixError> {
let members = [TAG_SYMBOL, TAG_SYMBOL_NAME, TAG_SYMBOL_DIGITS];
Ok(Self {
security_req_id: reader.required(TAG_SECURITY_REQ_ID)?,
security_response_id: reader.required(TAG_SECURITY_RESPONSE_ID)?,
result: reader.required(TAG_SECURITY_RESULT)?,
symbols: reader
.group(TAG_NO_RELATED_SYM, &members)?
.iter()
.map(|entry| {
Ok(SecurityEntry {
symbol: entry.required(TAG_SYMBOL)?,
name: entry.optional(TAG_SYMBOL_NAME)?,
digits: entry.optional(TAG_SYMBOL_DIGITS)?,
})
})
.collect::<Result<_, FixError>>()?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PositionReport {
pub pos_req_id: String,
pub position_id: Option<PositionId>,
pub total_reports: u32,
pub result: u32,
pub symbol: Option<SymbolId>,
pub settl_price: Option<Price>,
pub long_qty: Option<Volume>,
pub short_qty: Option<Volume>,
pub absolute_tp: Option<Price>,
pub absolute_sl: Option<Price>,
pub trailing_sl: Option<bool>,
pub trigger_method_sl: Option<u32>,
pub guaranteed_sl: Option<bool>,
}
impl PositionReport {
pub const MSG_TYPE: &'static str = "AP";
fn write(&self, out: &mut Vec<Field>) {
put(out, TAG_POS_REQ_ID, &self.pos_req_id);
put_optional(out, TAG_POSITION_ID, self.position_id.as_ref());
put(out, TAG_TOTAL_REPORTS, &self.total_reports);
put(out, TAG_POS_REQ_RESULT, &self.result);
put_optional(out, TAG_SYMBOL, self.symbol.as_ref());
put_optional(out, TAG_SETTL_PRICE, self.settl_price.as_ref());
if self.long_qty.is_some() || self.short_qty.is_some() {
put_count(out, TAG_NO_POSITIONS, 1);
}
put_optional(out, TAG_LONG_QTY, self.long_qty.as_ref());
put_optional(out, TAG_SHORT_QTY, self.short_qty.as_ref());
put_optional(out, TAG_ABSOLUTE_TP, self.absolute_tp.as_ref());
put_optional(out, TAG_ABSOLUTE_SL, self.absolute_sl.as_ref());
put_optional(out, TAG_TRAILING_SL, self.trailing_sl.as_ref());
put_optional(out, TAG_TRIGGER_METHOD_SL, self.trigger_method_sl.as_ref());
put_optional(out, TAG_GUARANTEED_SL, self.guaranteed_sl.as_ref());
}
fn read(reader: &Reader<'_>) -> Result<Self, FixError> {
Ok(Self {
pos_req_id: reader.required(TAG_POS_REQ_ID)?,
position_id: reader.optional(TAG_POSITION_ID)?,
total_reports: reader.required(TAG_TOTAL_REPORTS)?,
result: reader.required(TAG_POS_REQ_RESULT)?,
symbol: reader.optional(TAG_SYMBOL)?,
settl_price: reader.optional(TAG_SETTL_PRICE)?,
long_qty: reader.optional(TAG_LONG_QTY)?,
short_qty: reader.optional(TAG_SHORT_QTY)?,
absolute_tp: reader.optional(TAG_ABSOLUTE_TP)?,
absolute_sl: reader.optional(TAG_ABSOLUTE_SL)?,
trailing_sl: reader.optional(TAG_TRAILING_SL)?,
trigger_method_sl: reader.optional(TAG_TRIGGER_METHOD_SL)?,
guaranteed_sl: reader.optional(TAG_GUARANTEED_SL)?,
})
}
}
macro_rules! message_set {
($($name:ident: $doc:literal,)*) => {
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Message {
$(#[doc = $doc] $name($name),)*
ExecutionReport(Box<ExecutionReport>),
}
impl Message {
#[must_use]
pub const fn msg_type(&self) -> &'static str {
match self {
$(Self::$name(_) => $name::MSG_TYPE,)*
Self::ExecutionReport(_) => ExecutionReport::MSG_TYPE,
}
}
#[must_use]
pub fn body(&self) -> Vec<Field> {
let mut out = Vec::new();
match self {
$(Self::$name(message) => message.write(&mut out),)*
Self::ExecutionReport(message) => message.write(&mut out),
}
out
}
pub fn parse(msg_type: &str, body: &[Field]) -> Result<Self, FixError> {
$(if msg_type == $name::MSG_TYPE {
return $name::read(&Reader::new($name::MSG_TYPE, body)).map(Self::$name);
})*
if msg_type == ExecutionReport::MSG_TYPE {
return ExecutionReport::read(&Reader::new(ExecutionReport::MSG_TYPE, body))
.map(|report| Self::ExecutionReport(Box::new(report)));
}
Err(FixError::UnsupportedMessage(msg_type.to_owned()))
}
}
$(impl From<$name> for Message {
fn from(message: $name) -> Self {
Self::$name(message)
}
})*
};
}
message_set! {
Heartbeat: "Heartbeat (0).",
TestRequest: "Test request (1).",
ResendRequest: "Resend request (2).",
Reject: "Reject (3).",
SequenceReset: "Sequence reset (4).",
Logout: "Logout (5).",
Logon: "Logon (A).",
BusinessReject: "Business message reject (j).",
MarketDataRequest: "Market data request (V).",
MarketDataSnapshot: "Market data snapshot (W).",
MarketDataIncremental: "Market data incremental refresh (X).",
MarketDataReject: "Market data request reject (Y).",
SecurityListRequest: "Security list request (x).",
SecurityList: "Security list (y).",
NewOrderSingle: "New order single (D).",
OrderStatusRequest: "Order status request (H).",
OrderMassStatusRequest: "Order mass status request (AF).",
RequestForPositions: "Request for positions (AN).",
PositionReport: "Position report (AP).",
OrderCancelRequest: "Order cancel request (F).",
OrderCancelReject: "Order cancel reject (9).",
OrderCancelReplaceRequest: "Order cancel/replace request (G).",
}
impl From<ExecutionReport> for Message {
fn from(message: ExecutionReport) -> Self {
Self::ExecutionReport(Box::new(message))
}
}
impl Message {
#[must_use]
pub fn to_frame(&self, mut header: Header) -> Frame {
self.msg_type().clone_into(&mut header.msg_type);
Frame::new(header, self.body())
}
pub fn from_frame(frame: &Frame) -> Result<Self, FixError> {
Self::parse(&frame.header.msg_type, &frame.body)
}
#[must_use]
pub const fn is_administrative(&self) -> bool {
matches!(
self,
Self::Heartbeat(_)
| Self::TestRequest(_)
| Self::ResendRequest(_)
| Self::Reject(_)
| Self::SequenceReset(_)
| Self::Logout(_)
| Self::Logon(_)
)
}
}
#[cfg(test)]
#[path = "messages_tests.rs"]
mod tests;