OnixS C++ FIX Engine  4.12.0
API Documentation
Session.h
Go to the documentation of this file.
1 /*
2 * Copyright Onix Solutions Limited [OnixS]. All rights reserved.
3 *
4 * This software owned by Onix Solutions Limited [OnixS] and is protected by copyright law
5 * and international copyright treaties.
6 *
7 * Access to and use of the software is governed by the terms of the applicable OnixS Software
8 * Services Agreement (the Agreement) and Customer end user license agreements granting
9 * a non-assignable, non-transferable and non-exclusive license to use the software
10 * for it's own data processing purposes under the terms defined in the Agreement.
11 *
12 * Except as otherwise granted within the terms of the Agreement, copying or reproduction of any part
13 * of this source code or associated reference material to any other location for further reproduction
14 * or redistribution, and any amendments to this copyright notice, are expressly prohibited.
15 *
16 * Any reproduction or redistribution for sale or hiring of the Software not in accordance with
17 * the terms of the Agreement is a violation of copyright law.
18 */
19 
20 #pragma once
21 
22 #include <string>
23 #include <set>
24 #include <vector>
25 #include <utility>
26 #include <iosfwd>
27 #include <limits>
28 
32 
33 
35 
44 
46 
48 
51 
52 
53 namespace OnixS {
54 namespace FIX {
55 ONIXS_FIXENGINE_API_DECL(class, Message);
56 ONIXS_FIXENGINE_API_DECL(class, Dictionary);
57 ONIXS_FIXENGINE_API_DECL(class, Engine);
58 ONIXS_FIXENGINE_API_DECL(class, ISessionListener);
59 ONIXS_FIXENGINE_API_DECL(class, ISessionStorage);
60 
61 /// The session message mode.
62 struct MessageMode {
63  enum Enum {
64  /// The default mode. The `Message` class is used in inbound callbacks.
65  Message = 1,
66 
67  /// The `FlatMessage` class is used in inbound callbacks.
69  };
70 };
71 
72 namespace Core {
73 namespace Messaging {
74 class Message;
75 }
76 }
77 
78 template<typename MsgType>
80 {
82  typedef std::vector<FlatMessage*> MsgBatchType;
83  typedef std::vector<OnixS::FIX::Core::Messaging::Extras::FlatMessage*> CoreMsgBatchType;
84 };
85 
86 template<>
88 {
90  typedef std::vector<Message*> MsgBatchType;
91  typedef std::vector<OnixS::FIX::Core::Messaging::Message*> CoreMsgBatchType;
92 };
93 
94 /**
95 * The FIX Session - a bi-directional stream of ordered messages between two parties within a continuous sequence number series.
96 */
98 {
99 public:
100  /**
101  * Creates the FIX Session.
102  *
103  * @param senderCompId The assigned value used to identify the firm sending message (SenderCompID (tag=49) field value in outgoing messages).
104  * @param targetCompId The assigned value used to identify the receiving firm (TargetCompID (tag=56) field value in outgoing messages).
105  * @param dictionary The FIX dictionary to be used by the session.
106  * @param listener An instance of the ISessionListener interface, which will receive and handle miscellaneous Session events.
107  * @param storageType The session storage type.
108  * @param storage The pluggable session storage.
109  */
110  Session(
111  const std::string & senderCompId,
112  const std::string & targetCompId,
113  const Dictionary & dictionary,
114  ISessionListener * listener,
116  ISessionStorage * storage = ONIXS_FIXENGINE_NULLPTR);
117 
118  /**
119  * Creates the FIX Session.
120  *
121  * @param reactor An instance of an externally managed reactor.
122  * @param senderCompId The assigned value used to identify the firm sending message (SenderCompID (tag=49) field value in outgoing messages).
123  * @param targetCompId The assigned value used to identify the receiving firm (TargetCompID (tag=56) field value in outgoing messages).
124  * @param dictionary The FIX dictionary to be used by the session.
125  * @param listener An instance of the ISessionListener interface, which will receive and handle miscellaneous Session events.
126  * @param storageType The session storage type.
127  * @param storage The pluggable session storage.
128  */
129  Session(
130  ISessionReactor * reactor,
131  const std::string & senderCompId,
132  const std::string & targetCompId,
133  const Dictionary & dictionary,
134  ISessionListener * listener,
136  ISessionStorage * storage = ONIXS_FIXENGINE_NULLPTR);
137 
138  /**
139  * Creates the FIX Session.
140  *
141  * @param senderCompId The assigned value used to identify the firm sending message (SenderCompID (tag=49) field value in outgoing messages).
142  * @param targetCompId The assigned value used to identify the receiving firm (TargetCompID (tag=56) field value in outgoing messages).
143  * @param dictionary The FIX dictionary to be used by the session.
144  * @param keepSequenceNumbersAfterLogout The option to keep sequence numbers after the exchange of Logout (MsgType=5) messages.
145  * @param listener An instance of the ISessionListener interface which will receive and handle miscellaneous Session events.
146  * @param storageType The session storage type.
147  * @param storage The pluggable session storage.
148  */
149  Session(
150  const std::string & senderCompId,
151  const std::string & targetCompId,
152  const Dictionary & dictionary,
153  bool keepSequenceNumbersAfterLogout,
154  OnixS::FIX::ISessionListener * listener,
156  ISessionStorage * storage = ONIXS_FIXENGINE_NULLPTR);
157 
158 
159  /**
160  * Creates the FIX Session.
161  *
162  * @param reactor An instance of an externally managed reactor.
163  * @param senderCompId The assigned value used to identify the firm sending message (SenderCompID (tag=49) field value in outgoing messages).
164  * @param targetCompId The assigned value used to identify the receiving firm (TargetCompID (tag=56) field value in outgoing messages).
165  * @param dictionary The FIX dictionary to be used by the session.
166  * @param keepSequenceNumbersAfterLogout The option to keep sequence numbers after the exchange of Logout (MsgType=5) messages.
167  * @param listener An instance of the ISessionListener interface which will receive and handle miscellaneous Session events.
168  * @param storageType The session storage type.
169  * @param storage The pluggable session storage.
170  */
171  Session(
172  ISessionReactor * reactor,
173  const std::string & senderCompId,
174  const std::string & targetCompId,
175  const Dictionary & dictionary,
176  bool keepSequenceNumbersAfterLogout,
177  OnixS::FIX::ISessionListener * listener,
179  ISessionStorage * storage = ONIXS_FIXENGINE_NULLPTR);
180 
181  /**
182  * Creates the FIX Session.
183  *
184  * @param senderCompId The assigned value used to identify the firm sending message (SenderCompID (tag=49) field value in outgoing messages).
185  * @param targetCompId The assigned value used to identify the receiving firm (TargetCompID (tag=56) field value in outgoing messages).
186  * @param dictionary The FIX dictionary to be used by the session.
187  * @param keepSequenceNumbersAfterLogout The option to keep sequence numbers after the exchange of Logout (MsgType=5) messages.
188  * @param listener An instance of the ISessionListener interface which will receive and handle miscellaneous Session events.
189  * @param customSessionKey The custom key that can be used to distinguish sessions with the same values of the SenderCompID, TargetCompID and the FIX Protocol version.
190  * @param storageType The session storage type.
191  * @param storage The pluggable session storage.
192  */
193  Session(
194  const std::string & senderCompId,
195  const std::string & targetCompId,
196  const Dictionary & dictionary,
197  bool keepSequenceNumbersAfterLogout,
198  OnixS::FIX::ISessionListener * listener,
199  const std::string & customSessionKey,
201  ISessionStorage * storage = ONIXS_FIXENGINE_NULLPTR);
202 
203  /**
204  * Creates the FIX Session.
205  *
206  * @param reactor An instance of an externally managed reactor.
207  * @param senderCompId The assigned value used to identify the firm sending message (SenderCompID (tag=49) field value in outgoing messages).
208  * @param targetCompId The assigned value used to identify the receiving firm (TargetCompID (tag=56) field value in outgoing messages).
209  * @param dictionary The FIX dictionary to be used by the session.
210  * @param keepSequenceNumbersAfterLogout The option to keep sequence numbers after the exchange of Logout (MsgType=5) messages.
211  * @param listener An instance of the ISessionListener interface which will receive and handle miscellaneous Session events.
212  * @param customSessionKey The custom key that can be used to distinguish sessions with the same values of the SenderCompID, TargetCompID and the FIX Protocol version.
213  * @param storageType The session storage type.
214  * @param storage The pluggable Session storage.
215  */
216  Session(
217  ISessionReactor * reactor,
218  const std::string & senderCompId,
219  const std::string & targetCompId,
220  const Dictionary & dictionary,
221  bool keepSequenceNumbersAfterLogout,
222  OnixS::FIX::ISessionListener * listener,
223  const std::string & customSessionKey,
225  ISessionStorage * storage = ONIXS_FIXENGINE_NULLPTR);
226 
227  /**
228  * The destructor.
229  */
230  ~Session();
231 
232  /**
233  * Removes all messages from the outbound queue.
234  *
235  * @param removeFragmentedPacket The flag specifies whether to remove the last packet which is partially sent.
236  *
237  * @note This call is thread-safe.
238  */
239  Session & clearOutboundQueue(bool removeFragmentedPacket = false);
240 
241  /**
242  * Returns the Session's state.
243  *
244  * @note This call is thread-safe.
245  */
246  SessionState::Enum state() const;
247 
248  /**
249  * Returns the current encryption method.
250  *
251  * @note This call is thread-safe.
252  */
253  EncryptionMethod::Enum encryptionMethod() const;
254 
255  /**
256  * Sets the encryption method.
257  *
258  * @note This call is thread-safe.
259  */
260  Session & encryptionMethod(EncryptionMethod::Enum newEncryptionMethod);
261 
262  /**
263  * Returns the port to listen on for incoming FIX Connections in the Acceptor mode.
264  *
265  * @note This call is thread-safe.
266  */
267  int listenPort() const;
268 
269  /**
270  * Sets the port to listen on for incoming FIX Connections in the Acceptor mode.
271  *
272  * @note This call is thread-safe.
273  */
274  Session & listenPort(int listenPort);
275 
276  /**
277  * Returns the local network interface from which you intend to send and receive data.
278  *
279  * @note This call is thread-safe.
280  */
281  std::string localNetworkInterface() const;
282 
283  /**
284  * Sets the local network interface from which you intend to send and receive data.
285  *
286  * @note This call is thread-safe.
287  */
288  Session & localNetworkInterface(const std::string & localNetworkInterface);
289 
290  /**
291  * Returns the local port from which you intend to send and receive data.
292  *
293  * @note This call is thread-safe.
294  */
295  unsigned short localPort() const;
296  /**
297  * The local port range type.
298  */
299  typedef std::pair<unsigned short, unsigned short> LocalPortRange;
300 
301  /**
302  * Returns the local port range, the first available port from this range will be used to send and receive data.
303  *
304  * @note This call is thread-safe.
305  */
306  LocalPortRange localPortRange() const;
307 
308  /**
309  * Sets the local port range, the first available port from this range will be used to send and receive data.
310  *
311  * @note This call is thread-safe.
312  */
313  Session & localPortRange(LocalPortRange portRange);
314 
315  /**
316  * Returns the option to improve the latency at the expense of the message throughput (TCP_NODELAY socket option).
317  * When it is not set, the corresponding Engine setting's value is used ('true' by default).
318  */
319  bool tcpNoDelayOption() const;
320 
321  /**
322  * Sets the value of the option to improve the latency at the expense of the message throughput (TCP_NODELAY socket option).
323  */
324  Session & tcpNoDelayOption(bool improveLatency = true);
325 
326  /**
327  * Returns the option that controls whether to send the logout message before
328  * dropping the telecommunication link, in case of an exception.
329  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
330  */
331  bool sendLogoutOnException() const;
332 
333  /**
334  * Sets the value of the option that controls whether to send the logout message before
335  * dropping the telecommunication link, in case of an exception.
336  */
337  Session & sendLogoutOnException(bool sendLogoutOnException);
338 
339  /**
340  * Returns the option to validate the presence of unknown FIX messages.
341  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
342  */
343  bool validateUnknownMessages() const;
344 
345  /**
346  * Sets the option to validate the presence of unknown FIX messages.
347  */
348  Session & validateUnknownMessages(bool);
349 
350  /**
351  * Returns the option to validate the presence of unknown fields.
352  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
353  */
354  bool validateUnknownFields() const;
355 
356  /**
357  * Sets the option to validate the presence of unknown fields.
358  */
359  Session & validateUnknownFields(bool);
360 
361  /**
362  * Returns the option to validate the presence of required fields in inbound and outbound messages.
363  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
364  */
365  bool validateRequiredFields() const;
366 
367  /**
368  * Sets the option to validate the presence of required fields in inbound and outbound messages.
369  */
370  Session & validateRequiredFields(bool);
371 
372  /**
373  * Returns the option to validate the field values of FIX messages in accordance with the FIX protocol or its FIX Dictionary.
374  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
375  */
376  bool validateFieldValues() const;
377 
378  /**
379  * Sets the option to validate the field values of FIX messages in accordance with the FIX protocol or its FIX Dictionary.
380  */
381  Session & validateFieldValues(bool);
382 
383  /**
384  * Returns the option to validate the empty field values of FIX messages in accordance with the FIX protocol or its FIX Dictionary.
385  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
386  */
387  bool validateEmptyFieldValues() const;
388 
389  /**
390  * Sets the option to validate the empty field values of FIX messages in accordance with the FIX protocol or its FIX Dictionary.
391  */
392  Session & validateEmptyFieldValues(bool);
393 
394  /**
395  * Returns the option that controls the repeating group entry count validation.
396  * When it is not set, the corresponding Engine setting's value is used ('true' by default).
397  */
398  bool validateRepeatingGroupEntryCount() const;
399 
400  /**
401  * Sets the value of the option that controls the repeating group entry count validation.
402  */
403  Session & validateRepeatingGroupEntryCount(bool);
404 
405  /**
406  * Returns the option that controls the repeating group leading tag validation.
407  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
408  */
409  bool validateRepeatingGroupLeadingTag() const;
410 
411  /**
412  * Sets the value of the option that controls the repeating group leading tag validation.
413  */
414  Session & validateRepeatingGroupLeadingTag(bool);
415 
416  /**
417  * Returns the option that controls the duplicated field validation.
418  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
419  */
420  bool validateDuplicatedField() const;
421 
422  /**
423  * Sets value of the option that controls the duplicated field validation.
424  */
425  Session & validateDuplicatedField(bool);
426 
427  /**
428  * Returns the option that controls the validation of the checksum of the incoming message.
429  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
430  */
431  bool validateChecksum() const;
432 
433  /**
434  * Sets the validation of the checksum of the incoming message.
435  */
436  Session & validateChecksum(bool);
437 
438  /**
439  * Returns the number of messages that should be written to the outgoing TCP buffer together.
440  * When it is not set, the corresponding Engine setting's value is used (0 by default).
441  */
442  unsigned messageGrouping() const;
443 
444  /**
445  * Sets the number of messages that should be written to the outgoing TCP buffer together.
446  */
447  Session & messageGrouping(unsigned numberOfMessagesToGroup);
448 
449  /**
450  * Returns the connection mode.
451  */
452  ThreadingModel::Enum threadingModel() const;
453 
454  /**
455  * Sets the connection mode.
456  */
457  Session & threadingModel(ThreadingModel::Enum value);
458 
459  /**
460  * Returns whether the Session uses the spin lock.
461  */
462  bool useSpinLock() const;
463 
464  /**
465  * Sets the Session to use the spin lock.
466  */
467  Session & useSpinLock(bool value);
468 
469  /**
470  * Returns the reasonable transmission time as % from the heartbeatIntervalSec value.
471  * When it is not set, the corresponding Engine setting's value is used (20% by default).
472  */
473  int reasonableTransmissionTime() const;
474 
475  /**
476  * Sets the reasonable transmission time as % from the heartbeatIntervalSec value.
477  *
478  * When either end of the connection has not received any data for (heartbeatIntervalSec() * (100 + reasonableTransmissionTime())/100) seconds,
479  * it will transmit a Test Request message.
480  *
481  * If there is still no a Heartbeat message received after (heartbeatIntervalSec * (100 + reasonableTransmissionTime())/100) seconds
482  * then the connection should be considered lost and a corrective action be initiated.
483  */
484  Session & reasonableTransmissionTime(int value);
485 
486  /**
487  * Sets the number of attempts to restore the FIX connection.
488  */
489  Session & reconnectAttempts(int value);
490 
491  /**
492  * Returns the number of attempts to restore the FIX connection.
493  * When it is not set, the corresponding Engine setting's value is used (3 by default).
494  */
495  int reconnectAttempts() const;
496 
497  /**
498  * Sets the time interval between the attempts to restore the FIX connection (in seconds).
499  */
500  Session & reconnectInterval(int value);
501 
502  /**
503  * Returns the time interval between the attempts to restore the FIX connection (in seconds).
504  * When it is not set, the corresponding Engine setting's value is used (180 by default).
505  */
506  int reconnectInterval() const;
507 
508  /**
509  * Sets the non-blocking receive spinning timeout (in microseconds) before the receiving thread enters into the blocking wait mode.
510  *
511  * @note Should not be greater than 1 sec (minimal heartbeatIntervalSec()).
512  */
513  Session & receiveSpinningTimeoutUsec(int usec);
514 
515  /**
516  * Returns the current receive spinning timeout value (in microseconds).
517  * By default, the value is zero and the receive spinning is not used.
518  */
519  int receiveSpinningTimeout() const;
520 
521  /**
522  * Sets the send spinning timeout (in microseconds) of the Session::send(..) method to wait for the socket sending buffer availability
523  * in the spin loop mode before placing the message to the outgoing queue (to be sent later by the sending thread).
524  *
525  * @note Should not be greater than 1 sec (minimal heartbeatIntervalSec()).
526  */
527  Session & sendSpinningTimeoutUsec(int usec);
528 
529  /**
530  * Returns the current send spinning timeout value (in microseconds).
531  * By default, the value is zero and send spinning is not used.
532  */
533  int sendSpinningTimeout() const;
534 
535  /**
536  * Sets the NextExpectedMsgSeqNum field (tag 789) support in Logon messages.
537  */
538  Session & supportNextExpectedMsgSeqNum(bool support);
539 
540  /**
541  * Returns 'true' if the NextExpectedMsgSeqNum field (tag 789) is supported in Logon messages, otherwise - 'false'.
542  * By default, the option value is false.
543  */
544  bool supportNextExpectedMsgSeqNum() const;
545 
546  /**
547  * Returns the SSL certificate file.
548  *
549  * @note This call is thread-safe.
550  */
551  std::string sslCertificateFile() const;
552 
553  /**
554  * Sets the SSL certificate file.
555  *
556  * @note Only the (Privacy Enhanced Mail) Base 64 Encoded (.pem) SSL certificates are supported.
557  *
558  * @note This call is thread-safe.
559  */
560  Session & sslCertificateFile(const std::string & file);
561 
562  /**
563  * Returns the SSL private key file.
564  *
565  * @note This call is thread-safe.
566  */
567  std::string sslPrivateKeyFile() const;
568 
569  /**
570  * Sets the SSL private key file.
571  *
572  * @note Only the (Privacy Enhanced Mail) Base 64 Encoded (.pem) SSL certificates are supported.
573  *
574  * @note This call is thread-safe.
575  */
576  Session & sslPrivateKeyFile(const std::string & file);
577 
578  /**
579  * Returns the SSL private key file password.
580  *
581  * @note This call is thread-safe.
582  */
583  Cryptography::SecureString sslPrivateKeyPassword() const;
584 
585  /**
586  * Sets the SSL private key file password.
587  *
588  * @note This call is thread-safe.
589  */
590  Session & sslPrivateKeyPassword(const Cryptography::SecureString & password);
591 
592  /**
593  * Set the option to request peer certificates and perform the certificate verification.
594  *
595  * @note This call is thread-safe.
596  */
597  Session & sslVerifyPeer(bool verify);
598 
599  /**
600  * Returns the option to request peer certificates and perform the certificate verification.
601  * When it is not set, the corresponding Engine setting's value is used ('false' by default).
602  *
603  * @note This call is thread-safe.
604  */
605  bool sslVerifyPeer() const;
606 
607  /**
608  * Sets the client-side SNI-extension field.
609  * When is not empty, then this field provides SNI-name.
610  * When field value is "*" (wildcard), then SNI-name will be taken from the connection URL.
611  *
612  * @note Connection URL cannot be an IP address when the value "*" is used.
613  */
614  Session & sslClientSni(const std::string & hostName);
615 
616  /**
617  * Returns the client-side SNI-extension field.
618  */
619  const std::string & sslClientSni() const;
620 
621  /**
622  * Sets the path to the trusted certification authority certificate file in (Privacy Enhanced Mail) Base64 encoded (.pem) format.
623  *
624  * @note This call is thread-safe.
625  */
626  Session & sslCaFile(const std::string & value);
627 
628  /**
629  * Returns the path to the trusted certification authority certificate file in the (Privacy Enhanced Mail) Base64 encoded (.pem) format.
630  *
631  * @note This call is thread-safe.
632  */
633  std::string sslCaFile() const;
634 
635  /**
636  * Sets the minimal SSL/TLS protocol version that will be declared during the SSL/TLS handshake.
637  *
638  * @note This call is thread-safe.
639  */
640  Session & sslMinProtocolVersion(SslProtocolMinMaxVersion::Enum version);
641 
642  /**
643  * Returns the minimal SSL/TLS protocol version that will be declared during the SSL/TLS handshake.
644  *
645  * @note This call is thread-safe.
646  */
647  SslProtocolMinMaxVersion::Enum sslMinProtocolVersion() const;
648 
649  /**
650  * Sets the maximal SSL/TLS protocol version that will be declared during the SSL/TLS handshake.
651  *
652  * @note This call is thread-safe.
653  */
654  Session & sslMaxProtocolVersion(SslProtocolMinMaxVersion::Enum version);
655 
656  /**
657  * Returns the maximal SSL/TLS protocol version that will be declared during the SSL/TLS handshake.
658  *
659  * @note This call is thread-safe.
660  */
661  SslProtocolMinMaxVersion::Enum sslMaxProtocolVersion() const;
662 
663  /**
664  * Establishes the FIX Connection as an Acceptor.
665  *
666  * The Acceptor is the receiving party of the FIX session. It listens for the incoming connection on the pre-defined port.
667  * The acceptor has the responsibility to perform the first level authentication and formally declares
668  * the connection request "accepted" through the transmission of an acknowledgment Logon message.
669  *
670  * @note This call is thread-safe.
671  */
672  Session & logonAsAcceptor();
673 
674  /**
675  * Establishes the FIX Connection as an Initiator using the ResetSeqNumFlag (tag 141) field.
676  *
677  * The Initiator establishes the telecommunications link and initiates the session via the transmission
678  * of the initial Logon message.
679  * The method is blocked until the acknowledgment Logon message is received or the timeout expired.
680  * The timeout value is equal to the triple heartbeat interval.
681  *
682  * @note This call is thread-safe.
683  */
684  Session & logonAsInitiator(const std::string & host, int port, bool setResetSeqNumFlag);
685 
686  /**
687  * Establishes the FIX Connection as an Initiator.
688  *
689  * The Initiator establishes the telecommunications link and initiates the session via the transmission
690  * of the initial Logon message.
691  * The method is blocked until the acknowledgment Logon message is received or the timeout expired.
692  * The timeout value is equal to the triple heartbeat interval.
693  *
694  * @note This call is thread-safe.
695  */
696  Session & logonAsInitiator(const std::string & host, int port);
697 
698  /**
699  * Establishes the FIX Connection as an Initiator using the given Heartbeat interval (seconds).
700  * The method is blocked until the acknowledgment Logon message is received or the timeout expired.
701  * The timeout value is equal to the triple heartbeat interval.
702  *
703  * @note This call is thread-safe.
704  */
705  Session & logonAsInitiator(const std::string & host, int port, int heartbeatIntervalSec);
706 
707  /**
708  * Establishes the FIX Connection as an Initiator using the given Heartbeat interval (seconds) and the ResetSeqNumFlag(141) field.
709  * The method is blocked until the acknowledgment Logon message is received or the timeout expired.
710  * The timeout value is equal to the triple heartbeat interval.
711  *
712  * @note This call is thread-safe.
713  */
714  Session & logonAsInitiator(const std::string & host, int port, int heartbeatIntervalSec, bool setResetSeqNumFlag);
715 
716  /**
717  * Establishes the FIX Connection as an Initiator using the custom Logon message.
718  * The method is blocked until the acknowledgment Logon message is received or the timeout expired.
719  * The timeout value is equal to the triple heartbeat interval.
720  *
721  * @note This call is thread-safe.
722  */
723  Session & logonAsInitiator(const std::string & host, int port, int heartbeatIntervalSec, Message * customLogonMsg);
724 
725  /**
726  * Establishes the FIX Connection as an Initiator using the custom Logon message and the ResetSeqNumFlag(141) field.
727  * The method is blocked until the acknowledgment Logon message is received or the timeout expired.
728  * The timeout value is equal to the triple heartbeat interval.
729  *
730  * @note This call is thread-safe.
731  */
732  Session & logonAsInitiator(const std::string & host, int port, int heartbeatIntervalSec, Message * customLogonMsg, bool setResetSeqNumFlag);
733 
734  /**
735  * Establishes the FIX Connection asynchronously as an Initiator using the custom Logon message and the ResetSeqNumFlag(141) field.
736  * The method returns immediately without waiting the acknowledgment Logon message.
737  * Returns the `SharedFuture` object that can be used to wait for the result of the asynchronous logon method.
738  *
739  * @note This call is thread-safe.
740  */
741  Threading::SharedFuture<void> logonAsInitiatorAsync(const std::string & host, int port, int heartbeatIntervalSec, Message * customLogonMsg, bool setResetSeqNumFlag);
742 
743  /**
744  * Terminates the FIX Connection.
745  *
746  * The initial Logout message is sent to the counterparty and the method is blocked until the acknowledgment
747  * Logout message is received or the timeout expired.
748  * The timeout value is equal to the triple heartbeat interval or,
749  * in case there are no incoming messages, heartbeat interval plus reasonable transmission time.
750  *
751  * @note This call is thread-safe.
752  */
753  Session & logout();
754 
755  /**
756  * Terminates the FIX Connection.
757  *
758  * The initial Logout message is sent to the counterparty and the method is blocked until the acknowledgment
759  * Logout message is received or the timeout expired.
760  * The timeout value is equal to the triple heartbeat interval or,
761  * in case there are no incoming messages, heartbeat interval plus reasonable transmission time.
762  *
763  * @param text Free format text string that is sent to the counterparty in the Text(58) field of the initial
764  * Logout message.
765  *
766  * @note This call is thread-safe.
767  */
768  Session & logout(const std::string & text);
769 
770  /**
771  * Terminates the FIX Connection.
772  *
773  * The initial Logout message is sent to the counterparty and the method returns immediately
774  * without waiting for the acknowledgment Logout message.
775  * Returns the `SharedFuture` object that can be used to wait for the result of the asynchronous logout method.
776  *
777  * @param text The free format text string that is sent to the counterparty in the Text(58) field of the initial
778  * Logout message.
779  *
780  * @note This call is thread-safe.
781  */
782  Threading::SharedFuture<void> logoutAsync(const std::string & text);
783 
784  /**
785  * Terminates the FIX Connection.
786  *
787  * The initial Logout message is sent to the counterparty and the method is blocked until the acknowledgment
788  * Logout message is received or the timeout expired.
789  * The timeout value is equal to the triple heartbeat interval or,
790  * in case there are no incoming messages, the heartbeat interval plus reasonable transmission time.
791  *
792  * @param customLogoutMessage The custom Logout message that is sent to the counterparty.
793  *
794  * @note This call is thread-safe.
795  */
796  Session & logout(Message * customLogoutMessage);
797  Session & logout(FlatMessage * customLogoutMessage);
798 
799  /**
800  * Terminates the FIX Connection.
801  *
802  * The initial Logout message is sent to the counterparty and the method returns immediately
803  * without waiting the acknowledgment Logout message.
804  * Returns the `SharedFuture` object that can be used to wait for the result of the asynchronous logout method.
805  *
806  * @param customLogoutMessage The custom Logout message that is sent to the counterparty.
807  *
808  * @note This call is thread-safe.
809  */
810  Threading::SharedFuture<void> logoutAsync(Message * customLogoutMessage);
811  Threading::SharedFuture<void> logoutAsync(FlatMessage * customLogoutMessage);
812 
813  /**
814  * Terminates the FIX connection in the non-graceful way (without the exchange of Logout (MsgType=5) messages).
815  *
816  * @note This call is thread-safe.
817  */
818  Session & breakConnection();
819 
820  /**
821  * Sends the message to the counterparty.
822  *
823  * As soon as a session is created, it is possible to start sending messages via the session.
824  * If the session is not established, the messages are stored in the session storage and will be sent in replay to the resend request
825  * when the connection is established with the counterparty and the sequence numbers mismatch is detected.
826  *
827  * @note This call is asynchronous.
828  *
829  * @note This call is thread-safe.
830  */
831  Session & send(Message * msg);
832  Session & send(FlatMessage * msg);
833 
834  /**
835  * Performs sending via a specific API (e.g. zero-copy send) of the message to the counterparty.
836  *
837  * As soon as a session is created, it is possible to start sending messages via the session.
838  * If the session is not established, the messages are stored in the session storage and will be sent in replay to the resend request
839  * when the connection is established with the counterparty and the sequence numbers mismatch is detected.
840  *
841  * @note This call is asynchronous.
842  *
843  * @note This call is thread-safe.
844  */
845  Session & send(FlatMessage * msg, SessionSendMode::Enum mode);
846 
847  /**
848  * Message batch types.
849  */
850  template<typename MsgType> class MsgBatch;
851 
853  {
856 
857  static void init(MBT::CoreMsgBatchType & coreBatch);
858  static void init(SBT::CoreMsgBatchType & coreBatch);
859  static void add(MBT::MsgBatchType & batch, MBT::CoreMsgBatchType & coreBatch, MBT::MessagePtr & msg);
860  static void add(SBT::MsgBatchType & batch, SBT::CoreMsgBatchType & coreBatch, SBT::MessagePtr & msg);
861  static void clear(MBT::MsgBatchType & batch);
862  static void clear(SBT::MsgBatchType & batch);
863 
864  template<typename MsgType> friend class MsgBatch;
865  };
866 
867  template<typename MsgType>
868  class MsgBatch
869  {
870  typedef MsgBatchTraits<MsgType> Traits;
871 
872  friend class Session;
873 
874  typename Traits::MsgBatchType batch_;
875  typename Traits::CoreMsgBatchType coreBatch_;
876 
877  MsgBatch(const MsgBatch&);
878  MsgBatch & operator=(const MsgBatch&);
879 
880  public:
881 
882  typedef typename Traits::MessagePtr MessagePtr;
883  typedef typename Traits::MsgBatchType::iterator iterator;
884  typedef typename Traits::MsgBatchType::const_iterator const_iterator;
885 
886  MsgBatch() { MsgBatchHelper::init(coreBatch_); }
888 
889  void add(MessagePtr & msg) { MsgBatchHelper::add(batch_, coreBatch_, msg); }
890 
891  MsgType & operator[](size_t index) { return *batch_[index]; }
892  const MsgType & operator[](size_t index) const { return *batch_[index]; }
893 
894  size_t size() const { return batch_.size(); }
895 
896  const_iterator begin() const { return batch_.begin(); }
897  iterator begin() { return batch_.begin(); }
898 
899  const_iterator end() const { return batch_.end(); }
900  iterator end() { return batch_.end(); }
901  };
902 
905  typedef FlatMessageBatch SerializedMessageBatch;
906 
907  /**
908  * Sends messages in a batch to the counterparty.
909  *
910  * As soon as a session is created, it is possible to start sending messages via the session.
911  * If the session is not established, the messages are stored in the session storage and will be sent in replay to the resend request
912  * when the connection is established with the counterparty and the sequence numbers mismatch is detected.
913  *
914  *@param msgs The message batch to send.
915  *@param maxPacketSize The maximum number of bytes written to the socket's send buffer together.
916  * This parameter could be used to reduce the probability that the operating system will fragment a FIX message across multiple TCP packets.
917  *
918  * @note The message batch should not be empty and the maxPacketSize parameter should not be less than any message size in the batch.
919  * Otherwise, the method call can produce an error and the session can close the connection.
920  *
921  * @note This call is asynchronous.
922  *
923  * @note This call is thread-safe.
924  */
925  Session & send(MessageBatch & msgs, size_t maxPacketSize = (std::numeric_limits<size_t>::max)());
926  Session & send(FlatMessageBatch & msgs, size_t maxPacketSize = (std::numeric_limits<size_t>::max)());
927 
928  /**
929  * Performs sending via a specific API (e.g. zero-copy send) of messages to the counterparty.
930  *
931  * As soon as a session is created, it is possible to start sending messages via the session.
932  * If the session is not established, the messages are stored in the session storage and will be sent in replay to the resend request
933  * when the connection is established with the counterparty and the sequence numbers mismatch is detected.
934  *
935  * @note This call is asynchronous.
936  *
937  * @note This call is thread-safe.
938  */
939  Session & send(FlatMessageBatch & msgs, SessionSendMode::Enum mode, size_t maxPacketSize = (std::numeric_limits<size_t>::max)());
940 
941  /**
942  * Sends a serialized message(s) to the counterparty without any fields updating.
943  * One can use the preFill method to prepare a message(s) for sending.
944  *
945  * As soon as a session is created, it is possible to start sending messages via the session.
946  * If the session is not established, the messages are stored in the session storage and will be sent in replay to the resend request
947  * when the connection is established with the counterparty and the sequence numbers mismatch is detected.
948  *
949  * @note It checks the validity of the sequence number of the provided message.
950  * If the sequence number is incorrect, the sequence number, message length, and checksum will be updated during sending.
951  *
952  * @note This call is asynchronous.
953  *
954  * @note This call is thread-safe.
955  */
956  Session & sendAsIs(FlatMessage * msg);
957 
958  /**
959  * Sends a serialized message(s) to the counterparty without any fields updating.
960  * One can use the preFill method to prepare a message(s) for sending.
961  *
962  * As soon as a session is created, it is possible to start sending messages via the session.
963  * If the session is not established, the messages are stored in the session storage and will be sent in replay to the resend request
964  * when the connection is established with the counterparty and the sequence numbers mismatch is detected.
965  *
966  *@param msgs The message batch to send.
967  *@param maxPacketSize The maximum number of bytes written to the socket's send buffer together.
968  * This parameter could be used to reduce the probability that the operating system will fragment a FIX message across multiple TCP packets.
969  *
970  * @note The message batch should not be empty and the maxPacketSize parameter should not be less than any message size in the batch.
971  * Otherwise, the method call can produce an error and the session can close the connection.
972  *
973  * @note It checks the validity of the sequence number of the provided messages.
974  * If the sequence number is incorrect, the sequence number, message length, and checksum will be updated during sending.
975  *
976  * @note This call is asynchronous.
977  *
978  * @note This call is thread-safe.
979  */
980  Session & sendAsIs(FlatMessageBatch & msgs, size_t maxPacketSize = (std::numeric_limits<size_t>::max)());
981 
982  /**
983  * Performs the throttling of a session that must be called before each send function call.
984  * If the count of messages per time unit exceeds the throttling limit, the function will be blocked until the given time interval is passed.
985  *
986  * @note This call is thread-safe.
987  */
988  Session & throttle();
989 
990  /**
991  * Checks the throttling of a session that must be called before each send function call.
992  * If the count of messages per time unit exceeds the throttling limit, the function returns the delay (in milliseconds) until the sending becomes possible. Otherwise, it returns 0.
993  *
994  *@param resetWhenDelay The flag to indicate if the amount of messages per throttling interval should be reset when a delay is returned.
995  *
996  * @note This call is thread-safe.
997  */
998  size_t tryThrottle(bool resetWhenDelay = false);
999 
1000  /**
1001  * Sets throttling limit parameters.
1002  *
1003  *@param messagesCount The message limit per time unit.
1004  *@param intervalInMs The time interval to limit messages.
1005  *
1006  * @note This call is thread-safe.
1007  */
1008  Session & throttlingLimit(size_t messagesCount, size_t intervalInMs = 1000);
1009 
1010  /**
1011  * This method warms up the sending path.
1012  *
1013  *@param msg The message to warm up the assembly part of the sending path.
1014  *@param warmupFlags Specific flags which can be used to turn on the warmup feature for a specific NIC.
1015 
1016  * @note This call is thread-safe.
1017  */
1018  Session & warmUp(FlatMessage* msg, int warmupFlags = 0);
1019 
1020  /**
1021  * Returns 'true' if the given flags work as expected and a real data is not sent to the wire, otherwise - 'false'.
1022  *
1023  *@param warmupFlags Warmup flags for checking.
1024  *@param baseListenPort The base listen port to use during the checking.
1025  *@param localNetworkInterface The IP address to bind for listen and outgoing test sockets.
1026  *
1027  * @note This call is thread-safe.
1028  */
1029  static bool checkWarmupFlags(int warmupFlags, unsigned short baseListenPort = 5000, const std::string & localNetworkInterface = "127.0.0.1");
1030 
1031  /**
1032  * Pre-fills session-level fields that are constant during the session's lifetime - SenderCompId, TargetCompId, SenderLocationId, TargetLocationID, SenderSubID, TargetSubID.
1033  *
1034  * @note This call is thread-safe.
1035  */
1036  void preFill(Message & msg) const;
1037 
1038  /**
1039  * Pre-fills the following fields in the message or messages batch for sending as is:
1040  * - Session-level fields that are constant during the session's lifetime - SenderCompId, TargetCompId, SenderLocationId, TargetLocationI, SenderSubID, TargetSubID.
1041  * - The MsgSeqNum field in accordance with the session outgoing sequence number.
1042  * - The SendingTime field.
1043  * - BodyLength and CheckSum fields.
1044  *
1045  * @note This call is thread-safe.
1046  */
1047  void preFill(FlatMessage & msg) const;
1048  void preFill(FlatMessageBatch & msgs) const;
1049 
1050  /**
1051  * Shutdowns the session.
1052  *
1053  * @note This call is thread-safe.
1054  */
1055  Session & shutdown();
1056 
1057  /**
1058  * Returns the text description of this session.
1059  *
1060  * @note This call is thread-safe.
1061  */
1062  operator const std::string & () const;
1063 
1064  /**
1065  * Returns the underlying storage Id.
1066  *
1067  * @note This call is thread-safe.
1068  */
1069  const std::string & storageId() const;
1070 
1071  /**
1072  * Flushes all internal buffers of the underlying storage.
1073  *
1074  * @note This call is thread-safe.
1075  */
1076  Session & flushSessionStorage();
1077 
1078  /**
1079  * Returns the counterparty host name.
1080  *
1081  * @note The method performs a DNS request for the first time.
1082  * Therefore, it can block the thread execution for a long time until the DNS request is completed.
1083  *
1084  * @note This call is thread-safe.
1085  */
1086  std::string counterpartyHost() const;
1087 
1088  /**
1089  * Returns the counterparty address.
1090  *
1091  * @note This call is thread-safe.
1092  */
1093  std::string counterpartyIpAddress() const;
1094 
1095  /**
1096  * Returns the counterparty port number.
1097  *
1098  * @note This call is thread-safe.
1099  */
1100  size_t counterpartyPort() const;
1101 
1102  /**
1103  * Returns the Session's Custom Key.
1104  *
1105  * @note This call is thread-safe.
1106  */
1107  const std::string & customKey() const;
1108 
1109  /**
1110  * Returns the total number of bytes in the outbound queue.
1111  *
1112  * @note This call is thread-safe.
1113  */
1114  size_t outboundQueueBytes() const;
1115 
1116  /**
1117  * Returns the Heartbeat interval (in seconds).
1118  */
1119  int heartbeatIntervalSec() const;
1120 
1121  /**
1122  * Returns 'true' if inbound messages are logged, otherwise - 'false'.
1123  * By default, the value is 'true'.
1124  */
1125  bool logInboundMessages() const;
1126 
1127  /**
1128  * The option to log inbound messages.
1129  */
1130  Session & logInboundMessages(bool value);
1131 
1132  /**
1133  * Returns 'true' if outbound messages are logged, otherwise - 'false'.
1134  * By default, the value is 'true'.
1135  */
1136  bool logOutboundMessages() const;
1137 
1138  /**
1139  * The option to log outbound messages.
1140  */
1141  Session & logOutboundMessages(bool value);
1142 
1143  /**
1144  * Incoming message types to be filtered out from the logs.
1145  */
1146  typedef std::set<std::string> InboundMessageLogFilter;
1147 
1148  /**
1149  * Returns incoming message types to be filtered out from the logs.
1150  *
1151  * @note This call is thread-safe.
1152  */
1153  InboundMessageLogFilter inboundMessageLogFilter() const;
1154 
1155  /**
1156  * Sets incoming message types to be filtered out from the logs.
1157  *
1158  * @note This call is thread-safe.
1159  */
1160  Session & inboundMessageLogFilter(const InboundMessageLogFilter & filter);
1161 
1162  /**
1163  * Outgoing message types to be filtered out from the logs.
1164  */
1165  typedef std::set<std::string> OutboundMessageLogFilter;
1166 
1167  /**
1168  * Returns outgoing message types to be filtered out from the logs.
1169  *
1170  * @note This call is thread-safe.
1171  */
1172  OutboundMessageLogFilter outboundMessageLogFilter() const;
1173 
1174  /**
1175  * Sets outgoing message types to be filtered out from the logs.
1176  *
1177  * @note This call is thread-safe.
1178  */
1179  Session & outboundMessageLogFilter(const OutboundMessageLogFilter & filter);
1180 
1181  /**
1182  * Returns 'true' if outbound messages are logged before sending, otherwise - 'false'.
1183  * By default, the value is 'true'.
1184  *
1185  * @note This call is thread-safe.
1186  */
1187  bool logBeforeSending() const;
1188 
1189  /**
1190  * The option to switch on/off the logging of outbound messages before/after sending.
1191  *
1192  * @note This call is thread-safe.
1193  */
1194  Session & logBeforeSending(bool value);
1195 
1196  /**
1197  * Returns the expected sequence number of the next incoming message.
1198  *
1199  * @note This call is thread-safe.
1200  */
1201  SequenceNumber inSeqNum() const;
1202 
1203  /**
1204  * Sets the expected sequence number of the next incoming message.
1205  *
1206  * @note This call is thread-safe.
1207  */
1208  Session & inSeqNum(SequenceNumber seqNum);
1209 
1210  /**
1211  * Returns the sequence number of the next outgoing message.
1212  *
1213  * @note This call is thread-safe.
1214  */
1215  SequenceNumber outSeqNum() const;
1216 
1217  /**
1218  * Sets the sequence number of the next outgoing message.
1219  *
1220  * @note This call is thread-safe.
1221  */
1222  Session & outSeqNum(SequenceNumber seqNum);
1223 
1224  /**
1225  * Represents an unlimited number of messages to be requested in one Resend Request (MsgType=2) message.
1226  * The default value is 0.
1227  */
1228  static const unsigned int ResendRequestMaximumRangeNoLimit;
1229 
1230  /**
1231  * Sets the maximum number of messages to be requested in one Resend Request (MsgType=2) message.
1232  *
1233  * @see Session::ResendRequestMaximumRangeNoLimit.
1234  *
1235  * @param range The maximum number of messages to be requested in one Resend Request (MsgType=2) message. Cannot be negative.
1236  *
1237  * @note This call is thread-safe.
1238  */
1239  Session & resendRequestMaximumRange(int range);
1240 
1241  /**
1242  * Returns the maximum number of messages to be requested in one Resend Request (MsgType=2) message.
1243  * By default, the value is zero (no limit).
1244  *
1245  * @see Session::ResendRequestMaximumRangeNoLimit.
1246  *
1247  * @note This call is thread-safe.
1248  */
1249  int resendRequestMaximumRange() const;
1250 
1251  /**
1252  * Sets the number of sent messages that are available for resending on the counterparty's Resend Request <2> message.
1253  *
1254  * @note This call is thread-safe.
1255  */
1256  Session & resendingQueueSize(size_t value);
1257 
1258  /**
1259  * Returns the number of sent messages that are available for resending on the counterparty's Resend Request <2> message.
1260  * By default, the value is -1 that means that the corresponding Engine setting's value is used ('1000' by default).
1261  *
1262  * @note This call is thread-safe.
1263  */
1264  size_t resendingQueueSize() const;
1265 
1266  /**
1267  * Returns the session role.
1268  *
1269  * @note This call is thread-safe.
1270  */
1271  SessionRole::Enum role() const;
1272 
1273  /**
1274  * Returns the assigned value used to identify the firm sending message (the SenderCompID (tag 49) field value in outgoing messages).
1275  *
1276  * @note This call is thread-safe.
1277  */
1278  const std::string & senderCompId() const;
1279 
1280  /**
1281  * Returns 'true' if the LastMsgSeqNumProcessed (tag 369) field is specified on every message sent, otherwise - 'false'.
1282  * By default, the option value is false.
1283  */
1284  bool specifyLastMsgSeqNumProcessed() const;
1285 
1286  /**
1287  * The option to specify the LastMsgSeqNumProcessed (tag 369) field on every message sent.
1288  * Useful for detecting a backlog with a counterparty.
1289  *
1290  * @note The option does not affect the FlatMessage send.
1291  */
1292  Session & specifyLastMsgSeqNumProcessed(bool specify);
1293 
1294  /**
1295  * Returns 'true' if updating of the SendingTime is turn on for every message, otherwise - 'false'.
1296  * By default, the option value is true.
1297  */
1298  bool updateSendingTimeField() const;
1299 
1300  /**
1301  * The option to specify updating of the SendingTime of every sent message.
1302  */
1303  Session & updateSendingTimeField(bool specify);
1304 
1305  /**
1306  * Sets the time format of the SendingTime of every sent message.
1307  * By default, the YYYYMMDDHHMMSSMsec format is used.
1308  */
1309  Session & sendingTimeFormat(TimestampFormat::Enum format);
1310 
1311  /**
1312  * Returns the assigned value used to identify the receiving firm (the TargetCompID (tag 56) field value in outgoing messages).
1313  *
1314  * @note This call is thread-safe.
1315  */
1316  const std::string & targetCompId() const;
1317 
1318  /**
1319  * The instance of the FIX dictionary or standard FIX messages dictionary which is used by the session.
1320  */
1321  Dictionary dictionary() const;
1322 
1323  /**
1324  * Returns the CPU affinity of the receiving thread.
1325  */
1326  const OnixS::Threading::CpuIndexes & receivingThreadAffinity() const;
1327 
1328  /**
1329  * Sets the CPU affinity of the receiving thread.
1330  */
1331  Session & receivingThreadAffinity(const OnixS::Threading::CpuIndexes & cpuIndexes);
1332 
1333  /**
1334  * Sets the CPU affinity of the receiving thread to a CPU.
1335  */
1336  Session & receivingThreadAffinity(const OnixS::Threading::CpuIndex cpuIndex);
1337 
1338  /**
1339  * Returns the CPU affinity of the sending thread.
1340  */
1341  const OnixS::Threading::CpuIndexes & sendingThreadAffinity() const;
1342 
1343  /**
1344  * Sets the CPU affinity index of the sending thread.
1345  */
1346  Session & sendingThreadAffinity(const OnixS::Threading::CpuIndexes & cpuIndexes);
1347 
1348  /**
1349  * Sets the CPU affinity index of the sending thread a CPU.
1350  */
1351  Session & sendingThreadAffinity(const OnixS::Threading::CpuIndex cpuIndex);
1352 
1353  /**
1354  * Represents an undefined value of priority and policy.
1355  */
1356  static const int UndefinedPriorityAndPolicy;
1357 
1358  /**
1359  * Returns the priority of the receiving thread.
1360  */
1361  int receivingThreadPriority() const;
1362 
1363  /**
1364  * Sets the priority of the receiving thread.
1365  */
1366  Session & receivingThreadPriority(int priority);
1367 
1368  /**
1369  * Returns the priority of the sending thread.
1370  */
1371  int sendingThreadPriority() const;
1372 
1373  /**
1374  * Sets the priority of the sending thread.
1375  */
1376  Session & sendingThreadPriority(int priority);
1377 
1378  /**
1379  * Returns the scheduling policy of the receiving thread.
1380  */
1381  int receivingThreadPolicy() const;
1382 
1383  /**
1384  * Sets the scheduling policy of the receiving thread.
1385  */
1386  Session & receivingThreadPolicy(int policy);
1387 
1388  /**
1389  * Returns the scheduling policy of the sending thread.
1390  */
1391  int sendingThreadPolicy() const;
1392 
1393  /**
1394  * Sets the scheduling policy of the sending thread.
1395  */
1396  Session & sendingThreadPolicy(int policy);
1397 
1398  /**
1399  * Returns the sent message if it can be found by the given message sequence number, otherwise - NULL.
1400  *
1401  * @note The returned message is owned by the application and should be released after usage.
1402  *
1403  * @note This call is thread-safe.
1404  */
1405  Message * findSentMessage(SequenceNumber messageSequenceNumber);
1406  FlatMessage * findSentFlatMessage(SequenceNumber messageSequenceNumber);
1407 
1408  /**
1409  * Returns an array of sent messages if it can be found by the given message sequence number range, otherwise - empty array.
1410  *
1411  * @note The returned messages are owned by the application and should be released after usage.
1412  *
1413  * @note This call is thread-safe.
1414  */
1415  MsgBatchTraits<Message>::MsgBatchType findSentMessages(SequenceNumber beginSequenceNumber, SequenceNumber endSequenceNumber);
1416  MsgBatchTraits<FlatMessage>::MsgBatchType findSentFlatMessages(SequenceNumber beginSequenceNumber, SequenceNumber endSequenceNumber);
1417 
1418  /**
1419  * When the message gap is detected the "Resend Request" FIX Message is sent and the Session state is changed to "AwaitReplyOnResendRequest".
1420  * By default, in this state the incoming new messages (without the PossDupFlag (tag #43) flag) are ignored because we expect them to be re-sent later again with the PossDupFlag flag.
1421  *
1422  * This property allows to change this behavior and report the new messages anyway.
1423  *
1424  * @note In this mode, messages could be reported out of the original order: e.g. MsgSeqNum could be: 3 (original), 4 (original), 2 (PossDupFlag='Y'), 3 (PossDupFlag='Y'), 4 (PossDupFlag='Y')
1425  * and some messages could be received two times: first time without PossDupFlag='Y' and second time - with this flag.
1426  */
1427  Session & reportNewMessagesWhileWaitingForMissedMessages(bool report);
1428 
1429  /**
1430  * Returns 'true' if the new messages are reported even when the message gap is detected and the reply on the "Resend Request" message is expected, otherwise - 'false'.
1431  */
1432  bool reportNewMessagesWhileWaitingForMissedMessages() const;
1433 
1434  /**
1435  * By default, the "Resend Request" message is sent only once - when the first gap is detected.
1436  * This property allows to change this behavior and send the "Resend Request" message on each detected message sequence number gap.
1437  */
1438  Session & sendResendRequestOnEachMessageGap(bool send);
1439 
1440  /**
1441  * Returns 'true' if the "Resend Request" message is sent on each detected message sequence number gap, otherwise - 'false'.
1442  */
1443  bool sendResendRequestOnEachMessageGap() const;
1444 
1445  /**
1446  * By default, the "Resend Request" message requests all messages begin from the first missed one.
1447  * This property allows to change this behavior and request only missed messages.
1448  *
1449  * @note This method can be called only when the session is disconnected.
1450  */
1451  Session & requestOnlyMissedMessages(bool request);
1452 
1453  /**
1454  * Returns 'true' if the "Resend Request" message requests only missed messages, otherwise - 'false'.
1455  */
1456  bool requestOnlyMissedMessages() const;
1457 
1458  /**
1459  * By default, if the "Session Level Reject" message is received in replay to the "Resend Request" then this is considered as a serious problem and the FIX connection will be closed.
1460  * This property allows to change this behavior and consider the "Session Level Reject" on the "Resend Request" as the "Sequence Reset Gap Fill" message.
1461  */
1462  Session & considerRejectOnResendRequestAsGapFill(bool consider);
1463 
1464  /**
1465  * Returns 'true' if the "Reject" on the "Resend Request" is considered as the "Sequence Reset Gap Fill" message, otherwise - 'false'.
1466  */
1467  bool considerRejectOnResendRequestAsGapFill() const;
1468 
1469  /**
1470  * By default, if the incoming message has a sequence number less than expected and the PossDupFlag is not set, it indicates
1471  * a serious error and leads to FIX connection closing.
1472  * This property allows to change this behavior and consider the sequence number of the incoming message, which less than expected, as an expected one.
1473  */
1474  Session & ignoreLessThanExpectedSequenceNumber(bool ignore);
1475 
1476  /**
1477  * Returns 'true' if the sequence number of the incoming message, which less than expected, is considered as an expected one, otherwise - 'false'.
1478  */
1479  bool ignoreLessThanExpectedSequenceNumber() const;
1480 
1481  /**
1482  * The option to automatically reset the local sequence numbers to 1 during every logon.
1483  */
1484  Session & resetLocalSequenceNumbersOnLogon(bool reset);
1485 
1486  /**
1487  * Returns 'true' if local sequence numbers are reset automatically to 1 during every logon, otherwise - 'false'.
1488  */
1489  bool resetLocalSequenceNumbersOnLogon() const;
1490 
1491  /**
1492  * If the requestOnlyMissedMessages option is true and the sequence number of an incoming FIX message
1493  * greater that expected then the resend functionality is run and this incoming message is stored
1494  * in the incoming message gap queue for further processing.
1495  * This property allows to set maximum size of that queue.
1496  */
1497  Session & incomingMessageGapQueueMaximumSize(size_t maxSize);
1498 
1499  /**
1500  * Returns the maximum size of the incoming message gap queue.
1501  * By default, the value equal to 1000.
1502  */
1503  size_t incomingMessageGapQueueMaximumSize() const;
1504 
1505  /**
1506  * Registers the Session listener.
1507  *
1508  * @throw An exception if the listener is already registered.
1509  */
1510  Session & registerListener(ISessionListener * listener);
1511 
1512  /**
1513  * Unregisters the Session listener.
1514  */
1515  Session & unregisterListener(ISessionListener * listener);
1516 
1517  /**
1518  * Unregisters all Session listener.
1519  */
1520  Session & unregisterAllListeners();
1521 
1522  /**
1523  * Backups the current log files and resets the local sequence numbers to 1.
1524  *
1525  * @note This method can be called only when the session is disconnected.
1526  *
1527  * @note This call is thread-safe.
1528  */
1529  Session & resetLocalSequenceNumbers();
1530 
1531  /**
1532  * Sends a Logon message with the ResetSeqNumFlag set.
1533  *
1534  * @note This call is thread-safe.
1535  */
1536  Session & resetSeqNumViaLogonExchange();
1537 
1538  /**
1539  * Returns the SenderSubID (tag 50) field values for all outgoing messages.
1540  *
1541  * @note This call is thread-safe.
1542  */
1543  std::string senderSubId() const;
1544 
1545  /**
1546  * Sets the SenderSubID (tag 50) field values for all outgoing messages.
1547  *
1548  * @note This call is thread-safe.
1549  */
1550  Session & senderSubId(const std::string & value);
1551 
1552  /**
1553  * Returns the TargetSubID (tag 57) field values for all outgoing messages.
1554  *
1555  * @note This call is thread-safe.
1556  */
1557  std::string targetSubId() const;
1558 
1559  /**
1560  * Sets the TargetSubID (tag 57) field values for all outgoing messages.
1561  *
1562  * @note This call is thread-safe.
1563  */
1564  Session & targetSubId(const std::string & value);
1565 
1566  /**
1567  * Returns the SenderLocationID (tag 142) field values for all outgoing messages.
1568  *
1569  * @note This call is thread-safe.
1570  */
1571  std::string senderLocationId() const;
1572 
1573  /**
1574  * Sets the SenderLocationID (tag 142) field values for all outgoing messages.
1575  *
1576  * @note This call is thread-safe.
1577  */
1578  Session & senderLocationId(const std::string & value);
1579 
1580  /**
1581  * Returns the TargetLocationID (tag 143) field values for all outgoing messages.
1582  *
1583  * @note This call is thread-safe.
1584  */
1585  std::string targetLocationId() const;
1586 
1587  /**
1588  * Sets the TargetLocationID (tag 143) field values for all outgoing messages.
1589  *
1590  * @note This call is thread-safe.
1591  */
1592  Session & targetLocationId(const std::string & value);
1593 
1594  /**
1595  * Options to turn on/off incoming message sequence numbers validation.
1596  */
1597  Session & validateSequenceNumbers(bool value);
1598 
1599  /**
1600  * Returns the current status of the incoming message sequence numbers validation.
1601  * By default, the option value is true.
1602  */
1603  bool validateSequenceNumbers() const;
1604 
1605  /**
1606  * Returns the thread name suffix for receiving (R:threadNameSuffix) and sending (S:threadNameSuffix) threads.
1607  *
1608  * @note This call is thread-safe.
1609  */
1610  std::string threadNameSuffix() const;
1611 
1612  /**
1613  * Sets the thread name suffix for receiving ("R:threadNameSuffix") and sending ("S:threadNameSuffix") threads.
1614  **
1615  * If the threadNameSuffix is not specified, it is set by default to ("R:senderCompId-targetCompId")("S:senderCompId-targetCompId").
1616  **
1617  * @note This method can be called only when the session is disconnected.
1618  * @throw An exception if the session state is not Disconnected.
1619  *
1620  * @note This call is thread-safe.
1621  */
1622  Session & threadNameSuffix(const std::string & value);
1623 
1624  /**
1625  * Sends the Test Request (MsgType 1) message.
1626  * If the timeout is specified, the method blocks until the heartbeat message is received from the counterparty or timeout ended.
1627  *
1628  * @param testReqId The identifier included in the Test Request (MsgType 1) message to be returned in the resulting Heartbeat (MsgType 0) message from the counterparty.
1629  * @param timeout The maximum interval to wait until the reply is received from the counterparty.
1630  *
1631  * @note This call is thread-safe.
1632  */
1633  Session & sendTestRequest(const std::string & testReqId = "", const TimeSpan & timeout = TimeSpan::zero());
1634 
1635  /**
1636  * Sends the Resend Request (MsgType 2) message.
1637  *
1638  * @note Normally, the "Resend Request" message is sent automatically. This method allows to simulate a sequence gap by sending this message manually.
1639  * This can be needed in some venue specific cases. This method should not be used in the normal work.
1640  *
1641  * @param beginSeqNumber The begin sequence number of the first requested message in the range.
1642  *
1643  * @note This call is thread-safe.
1644  */
1645  Session & sendResendRequest(SequenceNumber beginSeqNumber);
1646 
1647  /**
1648  * Sends the Reject (MsgType 3) message.
1649  *
1650  * @param refSeqNumber The MsgSeqNum of rejected message.
1651  * @param text The message to explain the reason for the rejection.
1652  *
1653  * @note This call is thread-safe.
1654  */
1655  Session & sendReject(SequenceNumber refSeqNumber, const std::string & text);
1656 
1657  /**
1658  * Returns the time when logical session was created or the last sequence number reset operation was performed.
1659  * The originating value is extracted from the attached storage using the ISessionStorage::sessionCreationTime() method.
1660  *
1661  * @note This call is thread-safe.
1662  */
1663  Timestamp creationTime() const;
1664 
1665  /**
1666  * Returns the session string presentation.
1667  *
1668  * @note This call is thread-safe.
1669  */
1670  std::string toString() const;
1671 
1672  /**
1673  * Represents an invalid value of the socket handle.
1674  */
1676 
1677  /**
1678  * Returns the socket handle which the session uses to transmit the FIX data.
1679  *
1680  * @note This call is thread-safe.
1681  */
1682  OnixS::Sockets::Handle socketHandle();
1683 
1684  /**
1685  * Additional options, which should be set to the session socket when it is created.
1686  * For initiator sessions, options are set before the socket connect(..) call.
1687  * For acceptor sessions, options are set after the socket accept(..) call.
1688  */
1689  Session & socketOptions(const OnixS::Sockets::SocketOptions & options);
1690 
1691  /**
1692  * Inbound and outbound messages, the session's state data are stored in this directory.
1693  *
1694  * @note This method can be called only when the session is disconnected.
1695  * @throw An exception if the session state is not Disconnected.
1696  *
1697  * @note This call is thread-safe.
1698  */
1699  Session & logDirectory(const std::string & value);
1700 
1701  /**
1702  * Inbound and outbound messages, the session's state data are stored in this directory.
1703  *
1704  * @note This call is thread-safe.
1705  */
1706  const std::string & logDirectory() const;
1707 
1708  /**
1709  * Sets the timeout during which counterparty should send a reply to the "Resend Request" message.
1710  * If a counterparty does not reply or reply incorrectly during this timeout, then the ISessionListener::onWarning is called.
1711  * By default, the resend request timeout equal to zero, which means an infinite timeout.
1712  *
1713  * @note The resend timeout is checked when an incoming message is received or when the receive timeout is elapsed.
1714  * Therefore, the actual timeout can be greater than the specified one or can be rounded to the value equal to the heartbeat interval + reasonable transmission time.
1715  *
1716  * @note This call is thread-safe.
1717  */
1718  Session & resendTimeout(const TimeSpan & timeout);
1719 
1720  /**
1721  * Returns the timeout during which the counterparty should send a reply to the "Resend Request" message.
1722  *
1723  * @note This call is thread-safe.
1724  */
1725  TimeSpan resendTimeout() const;
1726 
1727  /**
1728  * The collection of scrambled tags.
1729  */
1730  typedef std::vector<Tag> ScrambledFields;
1731 
1732  /**
1733  * Sets scrambled fields in the Logon(A) message, in the session storage, for security reasons.
1734  *
1735  * @note This call is thread-safe.
1736  */
1737  Session & scrambleLogonFields(const ScrambledFields & fields);
1738 
1739  /**
1740  * Returns scrambled fields in the Logon(A) message.
1741  */
1742  ScrambledFields scrambleLogonFields() const;
1743 
1744  /**
1745  * Sets the send queue maximum size in bytes.
1746  * The TCP connection will be disconnected when an overflow issue happens and the sending queue size exceeds this size.
1747  *
1748  * @note This call is thread-safe.
1749  */
1750  Session & sendQueueMaxSize(size_t size);
1751 
1752  /**
1753  * Returns the send queue maximum size in bytes.
1754  * When it is not set, the corresponding Engine setting's value is used (0.5 GB by default).
1755  */
1756  size_t sendQueueMaxSize() const;
1757 
1758  /**
1759  * Sets the socket TCP connect timeout.
1760  *
1761  * @note This call is thread-safe.
1762  */
1763  Session & connectTimeout(const TimeSpan & timeout);
1764 
1765  /**
1766  * Returns the socket TCP connect timeout (30 sec by default).
1767  *
1768  * @note This call is thread-safe.
1769  */
1770  TimeSpan connectTimeout() const;
1771 
1772  /**
1773  * Returns the size of the TCP buffer allocated to the FIX connection for receiving data.
1774  * If '-1' then the default operating system value is used.
1775  *
1776  * @note This call is thread-safe.
1777  */
1778  int receiveBufferSize() const;
1779 
1780  /**
1781  * Sets the size of the TCP buffer allocated to the FIX connection for the receiving data.
1782  * If '-1' then the default operating system value is used.
1783  *
1784  * @note This call is thread-safe.
1785  */
1786  Session & receiveBufferSize(int value);
1787 
1788  /**
1789  * Returns the size of the TCP buffer allocated to the FIX connection for the sending data.
1790  * If '-1' then the default operating system value is used.
1791  *
1792  * @note This call is thread-safe.
1793  */
1794  int sendBufferSize() const;
1795 
1796  /**
1797  * Sets the size of the TCP buffer allocated to the FIX connection for the sending data.
1798  * If '-1' then the default operating system value is used.
1799  *
1800  * @note This call is thread-safe.
1801  */
1802  Session & sendBufferSize(int value);
1803 
1804  /**
1805  * Schedule the memory usage optimization.
1806  * The session will perform the actual memory usage optimization in two phases:
1807  * - After receiving and processing the next incoming session-level message (receiving part).
1808  * - Before sending the next outgoing session-level message (sending part).
1809  */
1810  void scheduleShrinkToFit();
1811 
1812  /**
1813  * HTTP proxy settings.
1814  */
1816  {
1818  :host(), port(), username(), password()
1819  {}
1820 
1821  ProxySettings(const std::string & proxyHost, int proxyPort, const std::string & proxyUsername = std::string(), const std::string & proxyPassword = std::string())
1822  :host(proxyHost), port(proxyPort), username(proxyUsername), password(proxyPassword)
1823  {}
1824 
1825  std::string host;
1826  int port;
1827  std::string username;
1828  std::string password;
1829  };
1830 
1831  /**
1832  * Sets HTTP proxy settings.
1833  */
1834  Session & proxySettings(const ProxySettings & settings);
1835 
1836  /**
1837  * Returns HTTP proxy settings.
1838  */
1839  ProxySettings proxySettings() const;
1840 
1841  /**
1842  * Returns the session message mode.
1843  */
1844  MessageMode::Enum messageMode() const;
1845 
1846  /**
1847  * Sets the session message mode.
1848  */
1849  void messageMode(MessageMode::Enum mode);
1850 
1851  struct Impl; ///< Implementation details.
1852 
1853 private:
1854  void init(
1855  const std::string & senderCompId,
1856  const std::string & targetCompId,
1857  const Dictionary & dictionary,
1858  ISessionListener * listener,
1859  bool keepSequenceNumbersAfterLogout,
1860  SessionStorageType::Enum storageType,
1861  ISessionStorage * storage,
1862  const std::string & customSessionKey,
1863  ISessionReactor * reactor);
1864 
1865  Impl * impl_;
1866 
1867  friend class Engine::Impl;
1868 };
1869 
1870 /// Stream output.
1872 std::ostream & operator << (std::ostream & os, const Session & session);
1873 }
1874 }
The FIX Session - a bi-directional stream of ordered messages between two parties within a continuous...
Definition: Session.h:97
The file based storage. The session&#39;s state and messages are persisted to the file system...
ONIXS_FIXENGINE_API std::ostream & operator<<(std::ostream &os, const Group &group)
Stream output.
Traits::MsgBatchType::iterator iterator
Definition: Session.h:883
MsgType & operator[](size_t index)
Definition: Session.h:891
std::set< std::string > InboundMessageLogFilter
Incoming message types to be filtered out from the logs.
Definition: Session.h:1146
static const OnixS::Sockets::Handle InvalidSocketHandle
Represents an invalid value of the socket handle.
Definition: Session.h:1675
const_iterator begin() const
Definition: Session.h:896
size_t CpuIndex
Logical processors that a thread is allowed to run on (first logical CPU has index 0)...
Definition: Thread.h:31
static TimeSpan zero()
The zero value of the time span.
int Handle
Type alias for socket handle.
Definition: Definitions.h:50
std::set< std::string > OutboundMessageLogFilter
Outgoing message types to be filtered out from the logs.
Definition: Session.h:1165
size_t size() const
Definition: Session.h:894
The session&#39;s Listener.
FlatMessageBatch SerializedMessageBatch
Definition: Session.h:905
std::vector< Tag > ScrambledFields
The collection of scrambled tags.
Definition: Session.h:1730
std::vector< OnixS::FIX::Core::Messaging::Message * > CoreMsgBatchType
Definition: Session.h:91
const MsgType & operator[](size_t index) const
Definition: Session.h:892
#define ONIXS_FIXENGINE_API
Definition: ABI.h:45
HTTP proxy settings.
Definition: Session.h:1815
const_iterator end() const
Definition: Session.h:899
PtrTraits< Message >::UniquePtr MessagePtr
Definition: Session.h:89
Provides an access to FIX fields from a flat (tag=value) message.
Definition: FlatMessage.h:109
virtual size_t resendingQueueSize() const =0
Returns the number of sent messages that are available for resending on counterparty&#39;s Resend Request...
Message batch types.
Definition: Session.h:850
ProxySettings(const std::string &proxyHost, int proxyPort, const std::string &proxyUsername=std::string(), const std::string &proxyPassword=std::string())
Definition: Session.h:1821
std::set< CpuIndex > CpuIndexes
Definition: Thread.h:32
MsgBatch< FlatMessage > FlatMessageBatch
Definition: Session.h:904
Identifies the FIX messages dictionary.
Definition: Dictionary.h:73
std::vector< Message * > MsgBatchType
Definition: Session.h:90
static const int UndefinedPriorityAndPolicy
Represents an undefined value of priority and policy.
Definition: Session.h:1356
Traits::MsgBatchType::const_iterator const_iterator
Definition: Session.h:884
The session message mode.
Definition: Session.h:62
ONIXS_FIXENGINE_API_DECL(class, IEngineListener)
virtual void clear()=0
Clears the storage.
The immutable secure string.
Definition: SecureString.h:29
std::pair< unsigned short, unsigned short > LocalPortRange
The local port range type.
Definition: Session.h:299
PtrTraits< MsgType >::UniquePtr MessagePtr
Definition: Session.h:81
The time span related functionality.
Definition: TimeSpan.h:93
std::vector< FlatMessage * > MsgBatchType
Definition: Session.h:82
MsgBatch< Message > MessageBatch
Definition: Session.h:903
The session&#39;s pluggable storage.
The session&#39;s network stack reactor interface.
unsigned int SequenceNumber
Alias for the sequence number.
std::vector< OnixS::FIX::Core::Messaging::Extras::FlatMessage * > CoreMsgBatchType
Definition: Session.h:83
Represents a future result of an asynchronous operation - a result that will eventually appear in the...
Definition: Future.h:253
Encapsulates operations over a FIX Message.
Definition: Message.h:49
virtual SequenceNumber outSeqNum()=0
Returns the last outgoing sequence number.
std::vector< SocketOption > SocketOptions
Storage type of socket options.
Definition: Definitions.h:67
std::auto_ptr< T > UniquePtr
Definition: Definitions.h:32
Traits::MessagePtr MessagePtr
Definition: Session.h:882
void add(MessagePtr &msg)
Definition: Session.h:889
The timestamps related functionality.
Definition: Timestamp.h:91
static const unsigned int ResendRequestMaximumRangeNoLimit
Represents an unlimited number of messages to be requested in one Resend Request (MsgType=2) message...
Definition: Session.h:1228
virtual SequenceNumber inSeqNum()=0
Returns the last inbound sequence number.