Introduction to FIX protocol

  javascript

Definition

FIX agreement is an open agreement provided by the International FIX Association. Its purpose is to promote the electronic process of international trade and establish a real-time electronic communication agreement among various participants, including investment managers, brokers, buyers and sellers. The goal of FIX protocol is to format the demand processes of various securities and financial services into functional processes that can be described by computer languages, and to exchange formats on each service functional interface in a unified way to facilitate the connection of various functional modules.

Working principle of protocol

Communication Model and Basic Concepts

Communication model

  • Initiator: Initiator, a participant who establishes a communication link and initiates a session by sending an initial Logon message.
  • Acceptor : recipient of the recipient FIX session. Responsible for performing the first level of authentication and formally declaring that the connec tion request is accepted by transmitting the confirmation of Logon message.
  • Principle: Initiator  is the first and Acceptor  is the recipient.
  • The standard mode uses the gateway as the Acceptor and the client as the Initiator as the common mode.

Fix connection

  • FIX connection consists of 3 parts: logon login, messagesexchange message transmission and logout logout.

    • Logon login

![](流程图/登陆.png)

- logout注销

![](流程图/注销.png)

Fix session

  • FIX sessions consist 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 th roughout the session. Monitoring the serial number enables session participants to identify and process lost messages, enabling fast application synchronization when reconnecting in a FIX session.
  • Each session will establish a set of independent accept and send sequences. Session participants will maintain a sequence assigned to send messages an d a message block gap sequence that monitors received messages.

Heartbeat

  • During message interaction, the FIX application will periodically generate Heartbeat messages. The heartbeat message can monitor the communication link status and identify gaps in received sequence numbers. The periodic interval for sending Heartbeat is defined by the session initiator using the HeartBtInt field in the Logon message.
  • The time interval for Heartbeat messages should be reset after each message is sent, i.e. after one message is sent, if no other message is sent within a given time interval, a Heartbeat message is sent. The value of HeartBtInt should be recognized by both sides of the conversation, defined by the initiator of the conversation and confirmed by the receiver of the conversation through a Logon message. The same HeartBtInt is used b y both sides of the conversation-the initiator of the login and the recipient of the login.

Data integrity check

  • The integrity of message data content can be verified in two ways: message length and validation code check.
  • The program performs integrity verification by calculating the number of characters from the BodyLength field to the CheckSum marker (“10=”) delimiter and comparing the message lengths marked by the field BodyLength.
  • ChekSum integrity check is obtained through calculation starting from “8” in the field “8=”, including the binary of each character of the delimiter < SOH > immediately following the CheckSum tag field and comparison with CheckSum.
  • A FIX message checksum is obtained by calculating the sum of each byte of the message to the checksum field (but not included). Then, the checksum is converted into a number of modulo 256 for transmission and comparison. Checksum is calculated after all encryption operations.
  • Verification code:
样例:8=FIX.4.29=7335=A34=149=CLIENT52=20181119-10:42:48.76856=SERVER98=0108=30141=Y10=208
1、消息长度:9=73
35=A34=149=CLIENT52=20181119-10:42:48.76856=SERVER98=0108=30141=Y(这段长度)
2、效验码检查
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, “%03d”, (unsigned int)( cks % 256 ) );
return( tmpBuf );
}

Message confirmation

  • The FIX protocol does not support confirmation of a single message. The method of monitoring message time slot is adopted for message recovery and verification.
  • Ordinary data transmission (no single message acknowledgement) is erroneously identified through message sequence gaps. Each message is marked by a unique serial number. The receiving application is responsible for monitoring the sequence number of the received message to identify message gaps and generate retransmission requests.
  • Each FIX participant must maintain two serial numbers for the FIX session, one is the receiving serial number and the other is the sending serial number, both of which are initialized to 1 when the FIX session is established. Each message is assigned a unique sequence number value and is incremented af ter the message is sent. In addition, each received message has a unique serial number, and the received serial number counter will be incremented after receiving each message.
  • When the received serial number does not need to be matched with the desired correct serial number, error correction processing must be taken.

Encryption

  • The encryption algorithm is negotiated by both parties.
  • Any domain of a message can be encrypted and placed in the SecureData domain. However, some displayed flag fields must be transmitted in clear text. To ensure integrity, the clear text domain can be repeated in the SecureData domain.
  • When encryption is used, it is recommended, but not required, that all message bodies be encrypted. If part of the data in the duplicate group data in a message is to be encrypted, the duplicate group must be encrypted in its entirety.
  • The pre-negotiated encryption algorithm is declared in the Logon message.

Custom field

  • FIX provides maximum flexibility to users. The FIX protocol allows users to customize fields. These domains are implemented and applied among identifi ed participants, and attention should be paid to avoid conflicts.
  • Tag numbers between 5000 and 9999 are reserved for user-defined fields. These tag values are used for information exchange of enterprise alliances. You can register through the FIX website.
  • More than 10,000 are reserved for internal use within a single enterprise. No registration required.

Message format

Data type

Integer int, floating point float, single character char, Boolean, String, data data

Domain

Common domain

Tag FieldName Remarks
8 BeginString Start string, FIX protocol version
9 BodyLength Message length
35 MsgType Message type: for example, F=Order Cancel Request, cancel the order.
11 ClOrdID Client order ID
37 OrderID Server order ID
41 OrigClOrdID Original client order ID
54 Side Type of business. For example: 1 = Buy, 2 = Sell
55 Symbol Stock code. For example: YRD
10 CheckSum Check code

Domain syntax

  • The beginning part should be the message header, followed by the text, and the end of the message.
  • The order of the first 3 fields of the message header cannot be changed: start 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 field (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, no domain other than the repeating group domain can repeat.

Security and Encryption

  • Because messages may be transmitted and exchanged on public networks or insecure networks, it is necessary to encrypt relevant sensitive data.
  • The specific encryption method is determined by the agreement reached between the connecting parties.
  • Any field in the message except some fields that need to be publicly identified for plaintext transmission can be encrypted to place the ciphertext data field.

(SecureData). Of course, these encrypted domains can also retain the clear text representation at the same time.

  • When deciding to use the encryption scheme, all domains in the message body can be encrypted. If part of the message’s repeating group needs to be encrypted, then the entire repeating group needs to be encrypted.
  • The protocol also provides some domains to support security technologies such as digital signature, key exchange and text encryption.

Message

Message header

Each session or application message has a message header indicating the message type, message body length, transmission destination, message sequence number, transmission starting point and transmission time.

Tag Domain name essential explain
8 BeginString Y Start string, value: FIX.4.2 (unencryptable, first field of message)
9 BodyLength Y Message body length (unencryptable, second field of message)
35 MsgType Y Message type (unencryptable, third field of message)
49 SenderCompID Y Sender code (unencryptable, sender identifier)
56 TargetCompID Y Receiver code (unencryptable, receiver identifier)
115 OnBehalfOfCompID N Initial sender identifier (encryptable) for sending via a third party.
128 DeliverToCompID N Final recipient identifier (encryptable) for transmission via a third party.
90 SecureDataLen N Ciphertext data length
91 SecureData N Ciphertext data (following the length field of ciphertext data)
34 MsgSeqNum Y Message sequence number (encrypted). If both parties to the transaction do not adopt FIX session mechanism, the tag can be set to a fixed value, such as 0.
50 SenderSubID N Sending Subprescription Identifier (Encryptable)
142 SenderLocationID N Sender Location Identifier (Encryptable)
57 TargetSubID N Receiving Subprescription Identifier (Encryptable)
143 TargetLocationID N Receiver Location Identifier (Encryptable)
116 OnBehalfOfSubID N The sub-identifier is initially sent (encryptable)
144 OnBehalfOfLocationID N Initial Sender Location Identifier (Encryptable)
129 DeliverToSubID N Final Receive Subidentifier (Encryptable)
145 DeliverToLocationID N Final Receiver Location Identifier (Encryptable)
43 PossDupFlag N The flag may be repeated. This flag shall be used when sending repeatedly. (Encryptable)
97 PossResend N The flag may be retransmitted. (Encryptable)
52 SendingTime Y Send Time (Encryptable)
122 OrigSendingTime N Original Send Time (Encryptable)
347 MessageEncoding N The character encoding type (non-ASCII) of the Encoded field in the message
369 LastMsgSeqNumProcesse d N Last processed message sequence number (encryptable)
370 OnBehalfOfSendingTime N Initial transmission time (time in UTC)

End of message

Each message (session or application message) has a message end and is terminated accordingly. The end of a message can be used to separate multiple messages and contains a 3-digit checksum value.

Tag Domain name essential explain
93 SignatureLength N Digital Signature Length (Non-Encryptable)
89 Signature N Digital Signature (Non-Encryptable)
10 CheckSum Y Checksum, the last field of the message. (Not Encryptable)

New order message (MsgType=D)

For order messages with PossResend flag set in the message header, the transaction customer order number (ClOrdID) core should be used
Whether the order has actually been received or not, the specific implementation shall also check the order parameters (buying and selling direction, securities code, quantity, etc.) for verification. If the order was received before, the order status should be responded to with an execution report message. If it has not been received before, it will respond to the order confirmation with an execution report message.
![](流程图/新订单.png)

Tag Domain name essential explain
Standard message header Y MsgType=D
11 ClOrdID Y The order number of the transaction client must be within the effective trading day of the order.
109 ClientID Y Customer capital account number
1 Account Y Customer transaction code
110 MinQty N Minimum turnover.
55 Symbol Y Futures contract code
167 SecurityType N FUT = futures
200 MaturityMonthYear N Used to specify the year and month when futures expire.
205 MaturityDay N Used for the maturity date of futures and used in conjunction with the maturity date (maturity month)
207 SecurityExchange Y Used to designate an exchange
77 OpenClose Y Indicate to open positions
8009 HedgeFlag Y Mark of speculative hedging
8010 TouchCondition N Trigger condition
54 Side Y Direction of buying and selling
38 OrderQty N Number of Entrusted Hands
60 TransactTime Y Order initiation time
40 OrdType Y Order type
44 Price N Price (Valid for Limit Orders)
423 PriceType N Price type
99 StopPx N Stop price
15 Currency N currency
59 TimeInForce N The effective time of the new order is the same day by default.
168 EffectiveTime N Used to specify when the order is valid.
432 ExpireDate N Conditionally used when the effective time (time information) = effective before a certain date (GTD) and no ExpireTime time is specified
126 ExpireTime N Conditionally used when the effective time (time information) = effective before a certain date (GTD) and the expiration date are not specified.
8096 MacNetInfo N The client’s machine network information
Standard end of message Y

Execution report message (MsgType=8)

  • Order confirmation
  • Confirmation of change in order status (e.g. confirmation of cancellation)
  • Send the transaction return of the order
  • Order rejection
Tag Domain name essential explain
Standard message header Y MsgType=8
37 OrderID Y The consignment number of a futures company must be unique on the same trading day.
11 ClOrdID N Transaction customer order number. If it is a strong flat return, the value will be the unique character string identifier of the current trading day beginning with “NONE”
41 OrigClOrdID N The original transaction customer order number, indicating the ClOrdID of the cancelled order.
17 ExecID Y The execution number of the futures company shall be the only guarantee on the effective trading day of the order.
150 ExecType Y Execution type
39 OrdStatus Y Order status
103 OrdRejReason N Required for order rejection
109 ClientID Y Customer capital account number
1 Account Y Customer transaction code
55 Symbol Y Futures contract code
167 SecurityType N FUT= futures
200 MaturityMonthYear N Maturity date
205 MaturityDay N Due date
207 SecurityExchange Y Used to designate an exchange
77 OpenClose N Indicate to open positions
54 Side Y Direction of buying and selling
38 OrderQty Y Number of Entrusted Hands
40 OrdType N Order type
44 Price N Order price
99 StopPx N Stop price
59 TimeInForce N The effective time of the new order is the same day by default.
15 Currency N currency
32 LastShares N Last Transaction Number (Last Transaction Number)
31 LastPx N Last Transaction Price (Last Transaction Price)
30 LastMkt N Last closing market
151 LeavesQty Y Remaining quantity of order
14 CumQty Y Total transactions
6 AvgPx Y Average transaction price
60 TransactTime N Execution time of report
381 GrossTradeAmt N Total transaction amount
110 MinQty N Minimum turnover
8500 OrderEntryTime N Order declaration time
8093 DeclarationID N Declaration number
8094 TradeID N Match number
Standard end of message 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, which returns the order status by executing the report message.

Tag Domain name essential explain
Standard message header Y MsgType=H
37 OrderID Y The consignment number of a futures company must be unique on the same trading day.
11 ClOrdID Y Transaction customer order number
109 ClientID Y Customer capital account number
1 Account Y Customer transaction code
55 Symbol Y Futures contract code
207 SecurityExchange Y Used to designate an exchange
167 SecurityType N FUT= futures
200 MaturityMonthYear N Used to specify the year and month when futures expire.
205 MaturityDay N Used for the maturity date of futures and used in conjunction with the maturity date (maturity month)
54 Side Y Direction of buying and selling
Standard end of message Y

Cancellation message (MsgType=F)

The cancellation message is used to cancel the remaining quantity of all orders.
The cancellation message is also given a ClOrdID, which can be regarded as another order. If rejected, withdraw the ClOrdID release of the rejection message.
The clorddid of the withdrawal message is set, while the clorddid of the original order is placed in the OrigClOrdID field. ClOrdID has to be unique.

Tag Domain name essential explain
Standard message header Y MsgType=F
41 OrigClOrdID Y The original transaction customer order number, indicating the ClOrdID of the cancelled order.
37 OrderID Y The consignment number of a futures company must be unique on the same trading day.
11 ClOrdID Y Transaction customer order number
109 ClientID Y Customer capital account number
1 Account Y Customer transaction code
55 Symbol Y Code of futures contract.
167 SecurityType N Securities code source
200 MaturityMonthYear N FUT= futures
205 MaturityDay N Futures expiration date
207 SecurityExchange Y Futures expiration date
54 Side Y Direction of buying and selling
60 TransactTime Y Order initiation time
40 OrdType Y Order type
38 OrderQty Y Number of Entrusted Hands
8093 DeclarationID N Declaration number
58 Text N
Standard end of message Y

Withdrawal Rejection Message (MsgType=9)

This message is used to reject the cancellation message.
When the transaction service party receives the cancellation notice and finds that it cannot execute (the completed order cannot be changed, etc.), it will send the cancellation notice to reject.
When rejecting the cancellation, the cancellation rejection message shall use clorddid to indicate the clorddid of the cancellation and OrigClOrdID to indicate the last order accepted before (unless the reason for rejection is “unknown order”).

Tag Domain name essential explain
Standard message header Y MsgType=9
37 OrderID Y The consignment number of a futures company must be unique on the same trading day.
11 ClOrdID Y Transaction customer order number
41 OrigClOrdID Y The original transaction customer order number, indicating the ClOrdID of the cancelled order.
39 OrdStatus Y Order status
109 ClientID Y Customer capital account number
1 Account Y Customer transaction code
60 TransactTime N Order initiation time
434 CxlRejResponseTo N Withdrawal Rejection Response Type
102 CxlRejReason N Reason for Rejection of Withdrawal
58 Text N
Standard end of message Y

FIX configuration

  • SESSION configuration
Configuration describe Valid value Default
BeginString FIX version number used by the session (start string for sending and receiving messages) FIXT.1.1、FIX.4.4、FIX.4.3、FIX.4.2、FIX.4.1、FIX.4.0
SenderCompID The ID of the party is defined in the session. Case-sensitive string
SenderSubID The ID number of the party associated with the session (optional) Case-sensitive string
SenderLocationID The locationID number of the party associated with the session (optional) Case-sensitive string
TargetCompID Opposite ID in this conversation Case-sensitive string
TargetSubID SubID of the opposite party in this conversation (optional) Case-sensitive string
TargetLocationID LocationID of the opposite party in this session (optional) Case-sensitive string
SessionQualifier An additional determiner is used to disambiguate and ensure the uniqueness of the conversation. Case-sensitive string
DefaultApplVerID Only required for FIXT1.1 (or above). Ignore transmission of earlier versions. Specifies the version ID of the default application for the session. Enumeration value of applvid (see applvid field for details), or 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 Define the role of the party in the session: acceptor or initiator initiator、acceptor
StartTime The effective start time of the session on the trading day when the FIX session is activated UTC time, format: HH:MM:SS
EndTime When the session expires on the trading day, the FIX session will be stopped UTC time, format: HH:MM:SS
StartDay For a week-long session configuration, the first day of the week’s session. Used in conjunction with STARTTIME. It is valid to use any abbreviation of the day of the week (for example, mo, mon, mond, monda,Monday are all valid)
EndDay For a week-long session configuration, the last day of the end of the week’s session. Used in conjunction with EndTime. It is valid to use any abbreviation of the day of the week (for example, mo, mon, mond, monda,Monday are all valid)
MillisecondsInTimeStamp Whether the timestamp adds milliseconds. FIX.4.2 and later versions are available. Y、N Y
ResetOnLogon Whether the serial number should be reset when receiving the login request. Only for Acceptor Y、N N
ResetOnLogout Do you want to reset the serial number when logging out normally Y、N N
ResetOnDisconnect Do you want to reset the serial number to 1 after abnormal disconnection Y、N N
RefreshOnLogon Determines whether the session state should be restored when logging in from the persistence layer. Useful when creating a hot failover session. Y、N N
EnableLastMsgSeqNumProcessed Whether to add the serial number of the last message in header (optional tag369). Y、N N
MaxMessagesInResendRequest Sets the maximum number of messages for a retransmission request. Any integer greater than 0. Use 0 as infinity (default). 0
SendLogoutBeforeDisconnectFromTimeout Specifies whether to send a logout message before disconnecting due to a timeout. Y、N N
IgnorePossDupResendRequests When PossDupFlag(tag 43) is set to true, whether to ignore a retransmission request Y、N N
  • Verify configuration
Configuration describe Valid value Default
UseDataDictionary Tells the session whether to use a data dictionary or not. If you want to use repeating group, you must use DataDictionary. Y、N Y
DataDictionary This configuration is only used for versions older than FIXT.1.1 Please refer to FIXT.1.1 for the configuration of TransportDataDictionary and AppDataDictionary in detail. FIX44.xml、FIX43.xml、FIX42.xml、FIX41.xml、FIX40.xml
TransportDataDictionary The XML definition file is used to validate incoming management messages. If DataDictionary is not provided, only the basic message will be verified. This configuration is only used for FIXT.1.1 (or later) sessions. FIXT1.1.xml
AppDataDictionary XML definition file used to validate application layer messages. Valid only for FIXT.1.1 (or later) sessions. For more information, please refer to the DataDictionary in (FIX.4.0 to FIX.4.4). This configuration can specify a custom applied data dictionary for each session. This configuration is only used for FIXT.1.1 or newer transport protocols. When FIXT transmission is used, this configuration can be used as a prefix for data dictionaries that specify multiple applications. For example: defaultapplicationversion id appdatadictionary = fix42.xml # for nondefault applicationversion id # Use BeginString suffix for app version AppDataDictionary.FIX.4.4=FIX44.xml A 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
ValidateFieldsOutOfOrder If 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. For systems with less stringent connection field requirements. Y、N Y
ValidateFieldsHaveValues If set to n, fields without values will not be rejected. Used to improperly send empty tags when connecting to the system. Y、N Y
ValidateUserDefinedFields If 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、N Y
  • Initiator
Configuration describe Valid value Default
ReconnectInterval The interval (in seconds) between attempts to reconnect. For initiator only. Positive integer 30
HeartBtInt Heartbeat interval (seconds). For initiator only. Positive integer
LogonTimeout Login timeout interval (seconds) Positive integer 10
LogoutTimeout Logout login timeout interval (seconds) Positive integer 2
SocketConnectPort Socket service port for establishing session. For initiator only Positive integer
SocketConnectHost Connect to host. initiator only X.x.x.x format IP address or domain name
SocketConnectPort<n> A set of spare Socket ports for failover of connection sessions, where n is a positive integer. SocketConnectPort1, SocketConnectPort2 … must be continuous and have a matching array SocketConnectHost<n > Positive integer
SocketConnectHost<n> A set of standby Socket service hosts for failover of connection sessions, n being a positive integer. SOCKETCONNECTHOST 1, SOCKETCONNECTHOST 2 … must be continuous and have a matching array SocketConnectPort<n > X.x.x.x format IP address or domain name
SocketNodelay Whether the connection disables Nagle algorithm. Configure node definitions in [DEFAULT]. Y、N Y
ReconnectInterval The interval (in seconds) between attempts to reconnect. For initiator only. Positive integer 30
  • Acceptor
Configuration describe Valid value Default
SocketAcceptPort Monitor the Socket port of the access connection. Acceptor only Positive integer, valid, open socket port
SocketAcceptHost The host that listens to the Socket service that accesses the connection. If not, acceptor will listen on all network ports (0.0.0.0) Valid x.x.x.x format IP address 0.0.0.0
SocketNodelay Whether the connection disables Nagle algorithm. Configure node definitions in [DEFAULT]. Y、N Y
  • Storage
Configuration describe Valid value 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 that you will never need to resend the message. Useful market data stream. Y、N Y
  • File Storage
Configuration describe Valid value Default
FileStorePath File directory where serial numbers and messages are stored. A valid file storage directory must have write permission.
  • Logging
Configuration describe Valid value Default
FileLogPath Directory where logs are stored. A valid file storage directory must have write permission.

FIX development

FIX engine

DEMO

  • Acceptor profile
# 定义会话的默认配置(default节点)
[DEFAULT]
FileStorePath=store
FileLogPath=log
ConnectionType=acceptor
ReconnectInterval=60
SenderCompID=SERVER
ResetOnDisconnect=Y
ResetOnLogout=Y
ResetOnLogon=Y

[SESSION]
BeginString=FIX.4.2
TargetCompID=CLIENT
StartTime=00:00:00
EndTime=23:59:59
HeartBtInt=30
SocketAcceptHost=127.0.0.1
SocketAcceptPort=6666
DataDictionary=FIX42.xml
  • Initiator profile
[DEFAULT]
ConnectionType=initiator
ReconnectInterval=60
FileLogPath=log
FileStorePath=store
StartTime=00:00:00
EndTime=23:59:59
HeartBtInt=30
ResetOnDisconnect=Y
ResetOnLogout=Y
ResetOnLogon=Y

[SESSION]
BeginString=FIX.4.2
SenderCompID=CLIENT
TargetCompID=SERVER
SocketConnectPort=6666
SocketConnectHost=127.0.0.1
DataDictionary=FIX42.xml
  • FixServer
package com.app.fix;

import quickfix.*;

/**
 * 服务启动主类(线程)
 */
public class FixServer {
    private static ThreadedSocketAcceptor acceptor = null;

    /**
     * 指定配置文件启动
     *
     * @param propFile
     * @throws ConfigError
     * @throws FieldConvertError
     */
    public FixServer(String propFile) throws ConfigError, FieldConvertError {
        // 设置配置文件
        SessionSettings settings = new SessionSettings(propFile);

        // 设置一个APPlication
        Application application = new FixServerApplication();

        /**
         *
         * quickfix.MessageStore 有2种实现。 quickfix.JdbcStore,quickfix.FileStore .
         * JdbcStoreFactory 负责创建JdbcStore , FileStoreFactory 负责创建FileStorequickfix
         * 默认用文件存储,因为文件存储效率高。
         */
        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();
    }

    /**
     * 测试本地使用的main方法
     *
     * @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: // 登陆
                    session.logon();
                    session.sentLogon();
                    break;
                case MsgType.HEARTBEAT: // 心跳
                    session.generateHeartbeat();
                    break;
            }

        } catch (FieldNotFound e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onCreate(SessionID sessionId) {
        System.out.println(" 服务器启动时候调用此方法创建");

    }

    @Override
    public void onLogon(SessionID sessionId) {
        System.out.println("客户端登陆成功时候调用此方法");

    }

    @Override
    public void onLogout(SessionID sessionId) {
        System.out.println("客户端断开连接时候调用此方法");

    }

    @Override
    public void toAdmin(Message message, SessionID sessionId) {
        System.out.println("发送会话消息时候调用此方法");

    }

    @Override
    public void toApp(Message message, SessionID sessionId) throws DoNotSend {
        System.out.println("发送业务消息时候调用此方法");

    }

    @Override
    public void fromAdmin(Message message, SessionID sessionId)
            throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, RejectLogon {
        System.out.println("接收会话类型消息时调用此方法");
        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("接收业务消息时调用此方法");
        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);
    }
}

Yixin Institute of Technology