In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article is about how to understand the principle, message format and configuration development of FIX protocol. I think it is very practical, so I share it with you. I hope you can get something after reading this article.
I. definition
FIX agreement is an open agreement provided by the International FIX Association, which aims to promote the process of electronic international trade and establish real-time electronic communication protocols among all kinds of participants, including investment managers, brokers, buyers and sellers. The goal of FIX protocol is to format all kinds of securities financial business requirements processes into functional processes that can be described by computer language, and to exchange a unified format on each business function interface to facilitate the connection of various functional modules.
II. The working principle of the protocol 2.1 Communication model and basic concepts
Communication model
Initiator: initiator, establishes a communication connection, and initiates the party of the session by sending the initial Logon message.
Acceptor: the recipient of the FIX session. Responsible for performing the first level of authentication and confirming that the connection request is accepted by transmitting the Logon message.
Principle: the initiator is Initiator and the recipient is Acceptor.
The standard mode takes the gateway as Acceptor and the client as Initiator as the common mode.
Fix connection
The FIX connection consists of three parts: logon login, message exchange message transmission, and logout logout.
Logon login
Logout logout
Fix session
A FIX session consists of one or more FIX Connection FIX connections. A FIX session can have multiple logins.
serial number
All FIX messages are marked by a unique serial number. The sequence number is initialized to 1 at the beginning of each FIX session and incremented throughout the session. Monitoring sequence numbers enables session participants to identify and process lost messages and quickly synchronize applications when reconnecting in a FIX session.
Each session establishes a set of independent accept and send sequences. The session participant maintains a sequence assigned to the sending message and a message block gap sequence number that monitors the receiving message.
heartbeat
During message interaction, FIX applications periodically generate Heartbeat heartbeat messages. The heartbeat message can monitor the communication link status and identify the received sequence number gap. The cycle interval for sending the Heartbeat is defined by the session initiator using the HeartBtInt field in the Logon message.
The interval of Heartbeat heartbeat messages should be reset after each message is sent, that is, after a message is sent, if no other messages are sent within a given interval, a Heartbeat heartbeat message is sent. The value of HeartBtInt should be agreed by both parties of the session, defined by the session initiator and confirmed by the session receiver through the Logon message. The same HeartBtInt is used by both sides of the session-the initiator and the recipient of the login.
Data integrity check
The integrity of the message data content can be verified in two ways: message length and validation code checking.
The program completes the integrity verification by calculating the number of characters from the BodyLock field to the CheckSum tag ("10 =") delimiter and comparing the message length marked by the domain BodyLength.
The ChekSum integrity check is obtained by calculating from "8" in the field "8 =", including the binary of each character of the delimiter immediately following the CheckSum tag field and comparing it with CheckSum.
An FIX message checksum is obtained by calculating the sum of each byte of the message to the ChechSum domain (but not including it). The checksum is then converted to a number of module 256 for transmission and comparison. The checksum is calculated after all encryption operations.
Check code:
Example: 8=FIX.4.29=7335=A34=149=CLIENT52=20181119-10:42:48.76856=SERVER98=0108=30141=Y10=2081, message length: 9=7335=A34=149=CLIENT52=20181119-10:42:48.76856=SERVER98=0108=30141=Y (this length) 2, validation code check char * GenerateCheckSum (char * buf, long bufLen) {static char tmpBuf [4]; long idx;unsigned int cks;for (idx = 0L, cks = 0; idx < bufLen; cks + = (unsigned int) buf [idx++]); sprintf (tmpBuf, "d", (unsigned int) (cks% 256)); return (tmpBuf);}
Message confirmation
The FIX protocol does not support the confirmation of a single message. The method of monitoring message slot is used for message recovery and verification.
Ordinary data transfer (no single message acknowledgement) is used for error identification through message sequence gaps. Each message is marked by a unique serial number. The receiver application is responsible for monitoring the sequence number of the received message to identify the message gap and generate retransmission requests.
Each FIX participant must maintain two sequence numbers for the FIX session, one is the receive sequence number and the other is the send sequence number, both of which are initialized to 1 at the beginning of establishing the FIX session. Each message is assigned a unique sequence number value and increments after the message is sent. In addition, each received message has a unique sequence number, and the received sequence number counter will be incremented after each message is received.
When the received sequence number does not have to match the correct sequence number you want, error correction must be taken.
Encrypt
The encryption algorithm is negotiated by both parties of the connection.
Any domain of a message can be encrypted and placed in the SecureDatadomain. However, some displayed flag fields must be transmitted in clear text. To ensure integrity, plaintext fields can be repeated in the SecureDatafield.
When encryption is used, it is recommended but not necessary that all message bodies are encrypted. If part of the duplicate group data in a message is to be encrypted, the duplicate group must all be encrypted.
The pre-negotiated encryption algorithm is declared in the Logon message.
Custom field
FIX provides maximum flexibility to users, and FIX protocol allows users to customize their domains. These domains are implemented and applied among identified participants, and care should be taken to avoid conflicts.
Tag numbers between 5000 and 9999 are reserved for user-defined domains. These tagged values are used for the exchange of information for enterprise alliances. You can register through the FIX website.
More than 10000 are reserved for internal use in a single enterprise. No need to register.
Message format 3.1 data types
Integer int, floating point float, single character char, Boolean Boolean, string String, data data
3.2 Domain
Common domain
Tag (tag) FieldName (domain name) Note 8BeginString start string, FIX protocol version 9BodyLength message length 35MsgType message type: for example, F=Order Cancel Request, cancel order 11ClOrdID client order ID37OrderID server order ID41OrigClOrdID original client order ID54Side transaction type. For example: 1 = Buy,2 = Sell55Symbol stock symbol. For example: YRD10CheckSum check code
Domain syntax
The beginning should be the message header, followed by the body, and finally the end of the message.
The order of the first three fields of the header cannot be changed: starting string (Tag = 8), message body length (Tag = 9), message type (Tag = 35)
The last field at the end of the message should be the checksum domain (Tag=10)
In a repeating group, the order in which domains appear should follow the order in which the repeating group is defined in the message or component.
In a message, any domain other than the repeating group domain cannot be repeated.
Security and encryption
Because messages may be transmitted and exchanged on public networks or insecure networks, it is necessary to encrypt the relevant sensitive data.
The specific method of encryption depends on the agreement reached between the two parties to the connection.
Any domain within a message except some domains that need to be publicly identified can be encrypted and placed in the ciphertext data field (SecureData). Of course, these encrypted fields can also be represented in plaintext.
When you decide to use an encryption scheme, you can encrypt all fields in the body of the message. If part of the repeating group of the message needs to be encrypted, the entire repeating group is required to be encrypted.
This protocol also provides some fields to support security technologies such as digital signature, key exchange and text encryption.
3.3 Messa
Message header
Each session or application message has a header that indicates the message type, message body length, sending destination, message sequence number, sending starting point, and sending time.
Tag domain name must specify 8BeginStringY starting string, value: FIX.4.2 (non-encrypted, first domain of message) 9BodyLengthY message body length (non-encrypted, second domain of message) 35MsgTypeY message type (non-encrypted, third domain of message) 49SenderCompIDY sender code (non-encrypted, sender identifier) 59TargetCompIDY receiver code (non-encrypted, receiver identifier) 115OnBehalfOfCompIDN initial sender identifier (encrypted) Used to send through a third party. 128DeliverToCompIDN final recipient identifier (encrypted) for sending through a third party. 90SecureDataLenN ciphertext data length 91SecureDataN ciphertext data (immediately following the ciphertext data length field) 34MsgSeqNumY message sequence number (encrypted). If both parties to the transaction do not use the FIX session mechanism, you can set the tag to a fixed value, such as 0. 50SenderSubIDN sender subidentifier (encryptable) 142SenderLocationIDN sender subidentifier (encryptable) 57TargetSubIDN receiver subidentifier (encryptable) 143TargetLocationIDN receiver subidentifier (encrypted) 116OnBehalfOfSubIDN initial sender subidentifier (encrypted) 144OnBehalfOfLocationIDN initial sender subidentifier (encrypted) 129DeliverToSubIDN final receiver subidentifier (encrypted) 145DeliverToLocationIDN final receiver azimuth identifier (encrypted) 43PossDupFlagN may repeat flag Make this mark. (encrypted) 97PossResendN may resend the flag. (encrypted) 52SendingTimeY sending time (encrypted) 122OrigSendingTimeN original sending time (encrypted) character encoding type (non-ASCII code) of Encoded domain in 347MessageEncodingN message 369LastMsgSeqNumProcesse dN last processed message sequence number (encrypted) 370OnBehalfOfSendingTimeN initial sending time (expressed in UTC)
Message tail
Each message (session or application message) has a message tail and is terminated. The message tail can be used to separate multiple messages and contain a three-digit checksum value.
Tag domain name must specify 93SignatureLengthN digital signature length (non-encrypted) 89SignatureN digital signature (non-encrypted) 10CheckSumY checksum, the last domain of the message. (not encrypted)
New order message (MsgType=D)
For the order message with the PossResend flag set in the message header, the transaction client order number (ClOrdID) should be used to verify whether the order has been received, and the order parameters (buying and selling direction, securities code, quantity, etc.) should be checked. If the order was previously received, the order status should be responded to with an execution report message. If it is not received before, respond to the order confirmation with an execution report message.
Tag domain name must be specified
Standard message header YMsgType=D11ClOrdIDY transaction customer order number, 109ClientIDY customer capital account number 1AccountY customer transaction code 110MinQtyN minimum transaction volume is required within the valid trading day of the order. 55SymbolY futures contract code 167SecurityTypeNFUT = futures 200MaturityMonthYearN is used to specify the year and month in which the futures expire, 205MaturityDayN is used for the expiration date of the futures, and 207SecurityExchangeY is used in conjunction with the expiration year and month (MaturityMonthYear) to specify the 77OpenCloseY of the designated exchange to open and close the 8009HedgeFlagY speculative hedging flag 8010TouchConditionN trigger condition 54SideY buying and selling direction 38OrderQtyN order number 60TransactTimeY order initiation time 40OrdTypeY order type 44PriceN price (valid for limit order) 423PriceTypeN price type 99StopPxN stop price 15CurrencyN currency 59TimeInForceN new order effective time The default is valid for the day 168EffectiveTimeN is used to specify the time when the order is valid 432ExpireDateN is conditionally used for the effective time (TimeInForce) = valid before a certain date (GTD), but without a specified deadline (ExpireTime), 126ExpireTimeN is conditionally used for the effective time (TimeInForce) = the machine network information of the 8096MacNetInfoN client is valid before a certain date (GTD) and the due date is not specified.
Standard message tail Y
Executive report message (MsgType=8)
Order confirmation
Confirmation of order status change (such as cancellation confirmation)
Send the transaction return of the order
Order rejection
Tag domain name must be specified
Standard message header YMsgType=837OrderIDY Futures Company order number, the same trading day must guarantee a unique 11ClOrdIDN trading client order number. In the case of Qiang Ping return, the value is the unique string on the trading day beginning with "NONE" to identify the 42OrigClOrdIDN original trading client order number, indicating the execution number of the ClOrdID17ExecIDY futures company whose order was cancelled. Within the valid trading day of the order, it shall be guaranteed that the only 150ExecTypeY execution type 39OrdStatusY order status 103OrdRejReasonN order rejection requires 109ClientIDY customer capital account number 1AccountY customer trading code 55SymbolY futures contract code 167SecurityTypeNFUT = futures 200MaturityMonthYearN expiry year month 205MaturityDayN expiration date 207SecurityExchangeY for the designated exchange 77OpenCloseN specified opening, closing 54SideY trading direction 38OrderQtyY order type 44PriceN order price 99StopPxN stop price 59TimeInForceN new order effective time The default is the last transaction number of the current valid 15CurrencyN currency 32LastSharesN (last transaction quantity) the last transaction price of 31LastPxN (the last transaction price) the remaining quantity of 151LeavesQtyY order in the last transaction market of 30LastMktN, the total transaction quantity of 14CumQtyY transaction, the average price of 6AvgPxY, the reporting time of 381GrossTradeAmtN transaction amount, the minimum transaction volume of 110MinQtyN, the order declaration time of 8093DeclarationIDN, the order number 8094TradeIDN matchmaking number.
Standard message tail Y
Order status request message (MsgType=H)
The order status request is used to request the status of an order from the transaction service party, and the transaction service party returns the order status through the execution report message.
Tag domain name must be specified
Standard message header YMsgType=H37OrderIDY futures company commission number, the same trading day must guarantee a unique 11ClOrdIDY trading client order number 109ClientIDY customer capital account number 1AccountY customer trading code 55SymbolY futures contract code 207SecurityExchangeY is used on the designated exchange 167SecurityTypeNFUT = futures 200MaturityMonthYearN to specify the year and month in which the futures expire 205MaturityDayN is used for the expiration date of the futures, and is used in conjunction with the expiration date (MaturityMonthYear) to use the 54SideY trading direction.
Standard message tail Y
Cancellation message (MsgType=F)
The cancellation message is used to cancel the remaining quantity of all orders.
The cancellation message is also assigned a ClOrdID, which can be regarded as another order. If rejected, the ClOrdID of the cancellation rejection message places the ClOrdID of the cancellation message, and the ClOrdID of the original order is placed in the OrigClOrdID domain. ClOrdID wants to make sure that the only thing.
Tag domain name must be specified
Standard message header YMsgType=F41OrigClOrdIDY original trading client order number, indicating the cancelled ClOrdID37OrderIDY futures company commission number, the same trading day must guarantee a unique 11ClOrdIDY trading client order number 109ClientIDY customer capital account number 1AccountY customer trading code 55SymbolY futures contract code 167SecurityTypeN securities code source 200MaturityMonthYearNFUT = futures 205MaturityDayN futures expiration date month 207SecurityExchangeY futures expiration date 54SideY futures order initiation time 40OrdTypeY order type 38OrderQtyY order number 8093DeclarationIDN order number 58TextN
Standard message tail Y
Order cancellation rejection message (MsgType=9)
This message is used for the rejection of the cancellation message.
When the transaction service party receives that the cancellation order can not be executed (the completed order cannot be changed, etc.), the transaction service party will send the cancellation order rejection.
When refusing to cancel an order, the cancellation rejection message applies ClOrdID to indicate the ClOrdID of the cancellation order and OrigClOrdID to indicate the last order accepted before (unless the rejection reason is an "unknown order").
Tag domain name must be specified
Standard message header YMsgType=937OrderIDY futures company commission number, the same trading day must guarantee a unique 11ClOrdIDY trading customer order number 41OrigClOrdIDY original trading customer order number, indicating the cancelled order status of the ClOrdID39OrdStatusY order 109ClientIDY customer capital account number 1AccountY customer transaction code 60TransactTimeN order initiation time 434CxlRejResponseToN cancellation rejection response type 102CxlRejReasonN cancellation rejection reason 58TextN
Standard message tail Y
FIX configuration 4.1session configuration (SESSION) configuration describes valid values default FIX version number (send and receive message start string) FIXT.1.1, FIX.4.4, FIX.4.3, FIX.4.2, FIX.4.1, FIX.4.0
A case-sensitive string that defines the local ID in a SenderCompID session
SenderSubID session-related local child ID number (optional) case-sensitive string
SenderLocationID session related local locationID number (optional) case-sensitive string
The ID case-sensitive string of the other party in the TargetCompID session
TargetSubID the other party in this session SubID (optional) case-sensitive string
TargetLocationID the other party in this session locationID (optional) case-sensitive string
A qualifier attached to SessionQualifier to eliminate ambiguity and ensure the uniqueness of the session as a case-sensitive string
DefaultApplVerID is only required for FIXT1.1 (or above). Ignore the transfer of previous versions. Specifies the default application version of the session, ID. The enumerated value of ApplVerID (see the ApplVerID field for details), or the default BeginString. FIX.5.0SP2 、 FIX.5.0SP1 、 FIX.5.0 、 FIX.4.4 、 FIX.4.3 、 FIX.4.2 、 FIX.4.1 、 FIX.4.0
ConnectionType defines the local party's role in the session: acceptor or initiatorinitiator, acceptor
The valid start time of the session on the StartTime trading day, when the FIX session is activated UTC time, format: HH:MM:SS
Session expiration time of EndTime trading day, FIX session will be stopped UTC time, format: HH:MM:SS
StartDay for a week-long session configuration, the first day of the week session begins. Used in conjunction with STARTTIME. Any abbreviation for the day of the week is valid (for example, mo, mon, mond, monda,Monday are valid)
EndDay for a week-long session configuration, the last day of the week session ends. Used in conjunction with EndTime. Any abbreviation for the day of the week is valid (for example, mo, mon, mond, monda,Monday are valid)
Whether milliseconds are added to the MillisecondsInTimeStamp timestamp. FIX.4.2 and later versions are available. Whether the serial number should be reset when Y and NYResetOnLogon receive the login request. It is only used when AcceptorY and NNResetOnLogout log out normally, whether the sequence number should be reset Y, whether the sequence number should be reset to 1Y if the NNResetOnDisconnect connection is disconnected abnormally, and NNRefreshOnLogon determines whether the session state should be restored when logging in from the persistence layer. Useful when creating a hot failover session. Whether Y and NNEnableLastMsgSeqNumProcessed add the sequence number of the last message to the header (optional tag369). Y and NNMaxMessagesInResendRequest set the maximum number of messages to resend the request at one time. Any integer greater than 0. Use 0 for infinity (default).
SendLogoutBeforeDisconnectFromTimeout specifies whether to send logout message Y, NNIgnorePossDupResendRequests before disconnecting due to a timeout, whether to ignore a retransmission request Y when PossDupFlag (tag 43) is set to true, NN4.2 verify configuration description valid values default UseDataDictionary tells the session whether to use a data dictionary, or not to use a data dictionary. If you want to use repeating group, you must use DataDictionary. Y, NYDataDictionary this configuration is only used for versions older than FIXT.1.1. Refer to the configuration of TransportDataDictionary and AppDataDictionary of FIXT.1.1 for details. FIX44.xml 、 FIX43.xml 、 FIX42.xml 、 FIX41.xml 、 FIX40.xml
The TransportDataDictionaryXML definition file is used to validate incoming administrative messages. If no DataDictionary is provided, only the basic message is validated. This configuration is used only for FIXT.1.1 (or later) sessions. FIXT1.1.xml
The XML definition file that AppDataDictionary uses to validate application layer messages. Valid only for FIXT.1.1 (or later) sessions. For more information, please refer to the DataDictionary (FIX.4.0 to FIX.4.4). This configuration can specify a custom applied data dictionary for each session. This configuration is used only for FIXT.1.1 or newer transport protocols. When using FIXT transport, this configuration can be used as a prefix to specify data dictionaries for multiple applications. For example: DefaultApplVerID=FIX.4.2 # For default application version ID AppDataDictionary=FIX42.xml # For nondefault application version ID # Use BeginString suffix for app version AppDataDictionary.FIX.4.4=FIX44.xml valid XML data dictionary file. QuickFIX/N is equipped with default protocol dictionary data: FIX50SP2.xml, FIX50SP1.xml, FIX50.xml, FIX44.xml, FIX43.xml, FIX42.xml, FIX41.xml, FIX40.xml
If ValidateFieldsOutOfOrder is set to N, the field placement area error (for example, the body field is in the header area, or the header field is in the body area) will not be rejected. Used to connect systems with less stringent field requirements. If Y and NYValidateFieldsHaveValues are set to N, fields with no value will not be rejected. Used to connect to the system and improperly send an empty label. If Y and NYValidateUserDefinedFields are set to N, user-defined fields will not be rejected, even if they are not defined in the data dictionary or do not appear in the message. Y, NY4.3 Initiator configuration describes the interval (in seconds) between valid values that ReconnectInterval attempts to reconnect by default. For initiator only. Positive integer 30HeartBtInt heartbeat interval in seconds. For initiator only. Positive integer-LogonTimeout login timeout interval (seconds) positive integer 10LogoutTimeout logout timeout interval (seconds) positive integer 2SocketConnectPortSocket service port, used to establish a session. For initiator positive integers only-SocketConnectHost to connect to the host. Used only for initiatorx.x.x.x format IP addresses or domain names-SocketConnectPort a set of alternate Socket ports for failover of connected sessions, where n is a positive integer. SocketConnectPort1,SocketConnectPort2... Must be contiguous and have a matching array of SocketConnectHost positive integers-SocketConnectHost a set of alternate Socket service hosts for the failover of the connection session, where n is a positive integer. SocketConnectHost1, SocketConnectHost2... Must be contiguous and have a matching array of SocketConnectPortx.x.x.x format IP addresses or domain names-whether the SocketNodelay connection disables the Nagle algorithm. Configure the node definition in [DEFAULT]. The interval between Y and NYReconnectInterval trying to reconnect (in seconds). For initiator only. A positive integer 304.4 Acceptor configuration describes the valid value default SocketAcceptPort snooping access connection Socket port. For acceptor positive integers only, valid, open socket ports-SocketAcceptHost listens to hosts accessing connected Socket services. If not, acceptor listens for all network ports (0.0.0.0) valid x.x.x.x format IP address 0.0.0.0SocketNodelay connections to disable the Nagle algorithm. Configure the node definition in [DEFAULT]. Y, NY4.5 Storage configuration description valid values default PersistMessages if set to N, the message will not be saved. This will force quickfix to always send GapFills instead of resending messages. Use this configuration if you know you will never need to resend the message. Useful market data streams. Y, NY4.6 File Storage configuration describes the valid values default FileStorePath stores serial numbers and messages in the file directory. A valid file storage directory must have write permission. -4.7 Logging configuration describes the directory where valid values default FileLogPath stores logs. A valid file storage directory must have write permission. -5. FIX develops 5.1 FIX engine
Official website: FIX engine (http://www.quickfixengine.org/)
Github:QFJ GitHub Repository (https://github.com/quickfix-j/quickfixj)
5.2 DEMO
Acceptor profile
# define the default configuration of the session (default node) [DEFAULT] FileStorePath=storeFileLogPath=logConnectionType=acceptorReconnectInterval=60SenderCompID=SERVERResetOnDisconnect=YResetOnLogout=YResetOnLogon= Y [session] BeginString=FIX.4.2TargetCompID=CLIENTStartTime=00:00:00EndTime=23:59:59HeartBtInt=30SocketAcceptHost=127.0.0.1SocketAcceptPort=6666DataDictionary=FIX42.xml
Initiator profile
[DEFAULT] ConnectionType=initiatorReconnectInterval=60FileLogPath=logFileStorePath=storeStartTime=00:00:00EndTime=23:59:59HeartBtInt=30ResetOnDisconnect=YResetOnLogout=YResetOnLogon= Y[SESSION] BeginString=FIX.4.2SenderCompID=CLIENTTargetCompID=SERVERSocketConnectPort=6666SocketConnectHost=127.0.0.1DataDictionary=FIX42.xml
FixServer
Package com.app.fix;import quickfix.*;/** * service startup main class (thread) * / public class FixServer {private static ThreadedSocketAcceptor acceptor = null; / * specify configuration file launch * * @ param propFile * @ throws ConfigError * @ throws FieldConvertError * / public FixServer (String propFile) throws ConfigError, FieldConvertError {/ / set configuration file SessionSettings settings = new SessionSettings (propFile) / / set an APPlication Application application = new FixServerApplication (); / * * quickfix.MessageStore has two implementations. Quickfix.JdbcStore,quickfix.FileStore. * JdbcStoreFactory is responsible for creating JdbcStore and FileStoreFactory is responsible for creating FileStorequickfix * File storage is used by default because of the high efficiency of file storage. * / MessageStoreFactory storeFactory = new FileStoreFactory (settings); LogFactory logFactory = new FileLogFactory (settings); MessageFactory messageFactory = new DefaultMessageFactory (); acceptor = new ThreadedSocketAcceptor (application, storeFactory, settings, logFactory, messageFactory);} private void startServer () throws RuntimeError, ConfigError {acceptor.start () } / * Test the main method used locally * * @ param args * @ throws FieldConvertError * @ throws ConfigError * / public static void main (String [] args) throws ConfigError, FieldConvertError {FixServer fixServer = new FixServer ("res/acceptor.config"); fixServer.startServer ();}}
FixServerApplication
Package com.app.fix;import quickfix.Application;import quickfix.DoNotSend;import quickfix.FieldNotFound;import quickfix.IncorrectDataFormat;import quickfix.IncorrectTagValue;import quickfix.Message;import quickfix.MessageCracker;import quickfix.RejectLogon;import quickfix.Session;import quickfix.SessionID;import quickfix.UnsupportedMessageType;import quickfix.field.MsgType;/** / public class FixServerApplication extends MessageCracker implements Application {@ Override protected void onMessage (Message message, SessionID sessionID) {try {String msgType = message.getHeader () .getString (35) Session session = Session.lookupSession (sessionID); switch (msgType) {case MsgType.LOGON: / / login session.logon (); session.sentLogon (); break; case MsgType.HEARTBEAT: / / heartbeat session.generateHeartbeat () Break;}} catch (FieldNotFound e) {e.printStackTrace ();} @ Override public void onCreate (SessionID sessionId) {System.out.println ("call this method to create when the server starts") } @ Override public void onLogon (SessionID sessionId) {System.out.println ("this method is called when the client logs in successfully");} @ Override public void onLogout (SessionID sessionId) {System.out.println ("call this method when the client disconnects") } @ Override public void toAdmin (Message message, SessionID sessionId) {System.out.println ("call this method when sending session messages");} @ Override public void toApp (Message message, SessionID sessionId) throws DoNotSend {System.out.println ("call this method when sending business messages") } @ Override public void fromAdmin (Message message, SessionID sessionId) throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, RejectLogon {System.out.println ("call this method when receiving a session type message"); try {crack (message, sessionId);} catch (UnsupportedMessageType | FieldNotFound | IncorrectTagValue e) {e.printStackTrace () } @ Override public void fromApp (Message message, SessionID sessionId) throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, UnsupportedMessageType {System.out.println ("call this method when receiving business messages"); crack (message, sessionId);}}
FixClient
Package com.app.fix;import quickfix.*;import quickfix.field.*;import quickfix.fix42.NewOrderSingle;import java.io.FileNotFoundException;import java.util.Date;public class FixClient implements Application {private static volatile SessionID sessionID; @ Override public void onCreate (SessionID sessionID) {System.out.println ("OnCreate");} @ Override public void onLogon (SessionID sessionID) {System.out.println ("OnLogon"); FixClient.sessionID = sessionID @ Override public void onLogout (SessionID sessionID) {System.out.println ("OnLogout"); FixClient.sessionID = null;} @ Override public void toAdmin (Message message, SessionID sessionID) {System.out.println ("ToAdmin");} @ Override public void fromAdmin (Message message, SessionID sessionID) throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, RejectLogon {System.out.println ("FromAdmin") } @ Override public void toApp (Message message, SessionID sessionID) throws DoNotSend {System.out.println ("ToApp:" + message);} @ Override public void fromApp (Message message, SessionID sessionID) throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, UnsupportedMessageType {System.out.println ("FromApp");} public static void main (String [] args) throws ConfigError, FileNotFoundException, InterruptedException, SessionNotFound {SessionSettings settings = new SessionSettings ("res/initiator.config") Application application = new FixClient (); MessageStoreFactory messageStoreFactory = new FileStoreFactory (settings); LogFactory logFactory = new ScreenLogFactory (true, true, true); MessageFactory messageFactory = new DefaultMessageFactory (); Initiator initiator = new SocketInitiator (application, messageStoreFactory, settings, logFactory, messageFactory); initiator.start (); while (sessionID = = null) {Thread.sleep (1000);} final String orderId = "342" NewOrderSingle newOrder = new NewOrderSingle (new ClOrdID (orderId), new HandlInst ('1'), new Symbol ("YRD"), new Side (Side.BUY), new TransactTime (new Date ()), new OrdType (OrdType.MARKET); Session.sendToTarget (newOrder, sessionID); Thread.sleep (5000) }} the above is how to understand the principle, message format and configuration development of the FIX protocol. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.