QuickfixJ: Broker OMS

In this tutorial, we are creating a simple Order Management System (OMS) template for a broker system.  The broker will utilize the MarketIntelligence class created in the last tutorial to simulate a market data source for bid and ask prices for securities on the Hong Kong Stock Exchange.  In order to implement the OMS with QuickfixJ, we will need to create two java classes, one for implementing a QuickfixJ application, and one for launching the application and supplying parameters to the application.  In this tutorial, our broker is Lan Fong Securities, an imaginary, boutique brokerage firm based in Hong Kong, and the client is Baker Street Capital, also an imaginary, London-based boutique investment firm.

Implementing a QuickfixJ application requires two steps.  The first step is to create a class deriving from quickfix.MessageCracker and implementing the quickfix.Application interface. To implement the interface, your class needs to override the following methods:

  • void onCreate(SessionID sessionID)
  • void onLogon(SessionID sessionID)
  • void onLogout(SessionID sessionID)
  • void toAdmin(Message msg, SessionID sessionID)
  • void fromAdmin(Message msg, SessionID sessionID)
  • void toApp(Message msg, SessionID sessionID)
  • void fromApp(Message msg, SessionID sessionID)

For more details, refer to the QuickfixJ documentation.  Lets just jump right in with the application class for the broker:

import java.io.*;
import java.util.*;

// Quickfix Exceptions
import quickfix.DoNotSend;
import quickfix.FieldConvertError;
import quickfix.ConfigError;
import quickfix.IncorrectDataFormat;
import quickfix.IncorrectTagValue;
import quickfix.FieldNotFound;
import quickfix.UnsupportedMessageType;
import quickfix.SessionNotFound;
import quickfix.RejectLogon;

// Quickfix Data Types
import quickfix.SessionID;
import quickfix.Message;
import quickfix.Session;
import quickfix.SessionSettings;
import quickfix.FixVersions;
import quickfix.MessageUtils;
import quickfix.field.*;

public class Application extends quickfix.MessageCracker
                         implements quickfix.Application
    private MarketIntelligence mi = null;

    public Application(SessionSettings settings)
        throws ConfigError, FieldConvertError
        mi = new MarketIntelligence();
        String ask = mi.getAsk("0001");

    // ===================================================
    // Overriden quickfix.MessageCracker onMessage()
    // ===================================================
    public void onMessage(quickfix.fix42.NewOrderSingle order,
                          SessionID sessionID)
        throws FieldNotFound, UnsupportedMessageType, IncorrectTagValue

    // ===================================================
    // quickfix.Application interface implementation
    // ===================================================

    // Called when quickfix creates a new session
    public void onCreate(SessionID sessionID)

    // notification that a valid logon has been established
    // with the countery party
    public void onLogon(SessionID sessionID)

    // notification that a FIX session is no longer online
    public void onLogout(SessionID sessionID)

    // allows for peaking at msgs from this apps FIX engine to
    // the counter party
    public void toAdmin(Message msg, SessionID sessionID)

    // callback notify for when admin msgs are received by FIX from
    // the counter party
    public void fromAdmin(Message msg, SessionID sessionID)
        throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue,
   // callback for app messages this app  send to the counter party
    public void toApp(Message msg, SessionID sessionID)
        throws DoNotSend

    // all app level requests comes through here
    public void fromApp(Message msg, SessionID sessionID)
        throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue,
        // call base class message parser
        crack(msg, sessionID);

In the constructor, a reference to a MarketIntelligence object is created, and we get the ask price for symbol 0001 just for testing.  Six of the seven interface methods are implemented but left blank as they are not used yet.  In the fromApp() method, the crack() method inherited from quickfix.MessageCracker is called.

The next step is to create a java class that acts as a QuickfixJ acceptor, a software component that waits for clients, called initiators, to connect and create a new FIX session.  This class is also responsible for passing parameters to the application class.  Again, it is probably easier to just jump into the code.

import java.io.*;
import java.util.*;

// Quickfix Exceptions
import quickfix.ConfigError;
import quickfix.FieldConvertError;
import quickfix.RuntimeError;

// Quickfix Data Types
import quickfix.SessionID;
import quickfix.SessionSettings;
import quickfix.SocketAcceptor;
import quickfix.mina.acceptor.DynamicAcceptorSessionProvider;
import quickfix.mina.acceptor.DynamicAcceptorSessionProvider.TemplateMapping;
import quickfix.DefaultMessageFactory;
import quickfix.FileStoreFactory;
import quickfix.LogFactory;
import quickfix.ScreenLogFactory;
import quickfix.MessageFactory;
import quickfix.MessageStoreFactory;

public class LanFongOMS
    private final SocketAcceptor acceptor;

    public LanFongOMS(SessionSettings settings)
        throws ConfigError, FieldConvertError
        Application app = new Application(settings);
        MessageStoreFactory msgStoreFactory = new FileStoreFactory(settings);
        LogFactory logFactory = new ScreenLogFactory(true, true, true);
        MessageFactory msgFactory = new DefaultMessageFactory();

        acceptor = new SocketAcceptor(app, msgStoreFactory, settings,
                                      logFactory, msgFactory);

    // Accept incoming connections
    public void start() throws RuntimeError, ConfigError

    // Stop accepting incoming connections
    public void stop()

    // Program entry-point
    public static void main( String args[] )
        SessionSettings sessionSettings = null;
            if( args.length != 1 ){
                System.err.println(" Usage: LanFongOMS ");
            sessionSettings = loadConfiguration(args[0]);
            Iterator sectionIterator = sessionSettings.sectionIterator();
            while( sectionIterator.hasNext() ){
                SessionID id = sectionIterator.next();
                System.out.println( id.toString() );

            LanFongOMS oms = new LanFongOMS(sessionSettings);
            System.out.println("press  to quit");
        catch( Exception ex ){
            System.err.println( "Exception!" );
            System.err.println( ex.getMessage() );

    // Load customer configuration from first argument
    private static SessionSettings loadConfiguration( String configFilePath )
        throws FileNotFoundException
        SessionSettings settings = null;
            InputStream inputStream = new FileInputStream(configFilePath);
            settings = new SessionSettings(inputStream);
        catch( Exception ex ){
            System.err.println( ex.getMessage() );

        return settings;


The code should be quite straight forward.  The entry point main() loads a configuration file taken as a command line argument and creates an instance of the broker’s OMS, which in turn creates a QuickfixJ application object in its constructor.  Back in main(), the acceptor is started that listens on a port number (from the config file) for incoming connections.  When the user at the controlling terminal presses the enter key, the acceptor is stopped and the OMS exists.

Before running the OMS, we need to update the ant build.xml file to support our new code.  The following modifications should suffice:

<target name=”jar” depends=”compile”>
<jar destfile=”LanFongOMS.jar” basedir=”.” includes=”**/*.class”>
<attribute name=”Main-Class” value=”LanFongOMS”/>

<target name=”run” depends=”jar”>
<java classname=”LanFongOMS” fork=”true”>
<classpath refid=”project.class.path”/>
<arg value=”lanfong.cfg”/>

Basically, we need to update the jar target to specify the java file containing the entry point function for the JAR manifest, and we need to specify the argument for the OMS, a configuration file (lanfong.cfg).

Now that all of the code has been implemented, we must supply a config file that sets the application specific parameters for the QuickfixJ application.  One field of interest is ConnectionType, which can be set to acceptor or initiator.  In our example, the customer, Baker St. Capital, will connect to its broker, Lan Fong Securities, and thus they are initiator and acceptor, respectively.



Other fields of interest are SenderCompID and TargetCompID, which specify the source and target of FIX messages.  Also of interest is the BeginString in the session section.  We use FIX version 4.2, but you could use any version of the FIX protocol supported by QuickfixJ, or even supported multiple versions of the FIX protocol in one config file.  Note that Quickfix sessions are identified as a combination of BeginString, SenderCompID and TargetCompID.  There are many, many more parameters that we can set, so please refer to the documentation for further information about config files.

Finally, we can bring up the Lan Fong Securities OMS:

trantor:quickfix_demo$ ant
Buildfile: build.xml

    [javac] Compiling 5 source files

      [jar] Building jar: /Users/globalengineer/Development/quickfix_demo/LanFongOMS.jar

     [java] FIX.4.2:LANFONG->BAKERST
     [java] 41.59
     [java] <20100429-03:59:35, FIX.4.2:LANFONG->BAKERST, event> (Session FIX.4.2:LANFONG->BAKERST schedule is daily, 08:00:00 UTC - 19:00:00 UTC (daily, 08:00:00 UTC - 19:00:00 UTC))
     [java] <20100429-03:59:35, FIX.4.2:LANFONG->BAKERST, event> (Session state is not current; resetting FIX.4.2:LANFONG->BAKERST)
     [java] <20100429-03:59:35, FIX.4.2:LANFONG->BAKERST, event> (Created session: FIX.4.2:LANFONG->BAKERST)
     [java] Apr 28, 2010 11:59:35 PM quickfix.mina.NetworkingOptions logOption
     [java] INFO: Socket option: SocketTcpNoDelay=true
     [java] Apr 28, 2010 11:59:35 PM quickfix.mina.NetworkingOptions logOption
     [java] INFO: Socket option: SocketSynchronousWrites=false
     [java] Apr 28, 2010 11:59:35 PM quickfix.mina.NetworkingOptions logOption
     [java] INFO: Socket option: SocketSynchronousWriteTimeout=30000
     [java] Apr 28, 2010 11:59:35 PM quickfix.mina.acceptor.AbstractSocketAcceptor startAcceptingConnections
     [java] INFO: Listening for connections at /
     [java] press  to quit

Though our OMS does not do anything at this point, it has been brought up and is listening for incoming connections.  Notice that the quote retrieved from the market data source in the application’s class is printed out in the second line of the application output.  In the next installment of this tutorial, we’ll implement the a simple OMS for the client that acts as a QuickfixJ initiator and connects to our broker’s OMS.  Stay tuned!


QuickfixJ: data source simulator

Before getting started with QuickfixJ, in order to simulate market data on the broker side, we need some sort of data source that provides bid and ask prices on demand.  We could use historical data, but in order to keep things interesting lets use randomly generated data.  We will create an object titled MarketIntelligence, which the broker uses to generate quotes for customers.

Symbols on the Hong Kong Stock Exchange are based on numbers and not letters like NYSE, which makes the job of generating the symbols on the fly very easy.  We’ll limit the set of symbols to 1 through 1000, and prices will be updated every 200ms based on java.util.Timer timeouts.  Prices will randomly generated in the range of 0 to 500, and will be increased or decreased in small increments to simulate the movement of the security on the stock exchange.  The code for the MarketIntelligence object is sweet and simple:

import java.util.Random;
import java.util.Map;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

public class MarketIntelligence
    private static final int maxPrice = 500;
    private Random generator;
    private HashMap bids;
    private HashMap asks;

        bids = new HashMap();
        asks = new HashMap();
        generator = new Random();

        // Generate some random symbols
        Integer basePrice;
        Double decimal, price;
        String symbol, bid_price, ask_price;
        for( int index=1; index<1000; index++)
            basePrice = generator.nextInt(maxPrice);
            decimal = generator.nextDouble();
            price = basePrice.doubleValue() + decimal;
            symbol = String.format("%04d", index);
            bid_price = String.format("%.2f",price);
            ask_price = String.format("%.2f",price+0.01);
            bids.put(symbol, bid_price);
            asks.put(symbol, ask_price);

        // Update market data every 200 ms
        Timer timer = new Timer();
        TimerTask task = new TimerTask(){
             public void run(){
        timer.scheduleAtFixedRate( task, 0, 200 );


    public String getBid(String symbol)
        return bids.get(symbol);

    public String getAsk(String symbol)
        return asks.get(symbol);

    public void update()
        Double current_bid, current_ask, new_bid, new_ask;
        Double delta, price;
        Integer up_dn;
        String current_key;

        for(Map.Entry entry : bids.entrySet())
            current_key = entry.getKey();
            current_bid = Double.parseDouble(bids.get(current_key));
            current_ask = Double.parseDouble(asks.get(current_key));

            delta = generator.nextDouble();
            up_dn = generator.nextInt() % 2;
            delta = up_dn.doubleValue() * delta;
            new_bid = current_bid + delta;
            new_ask = new_bid + 0.1;

            bids.put(current_key, String.format("%.2f", new_bid));
            asks.put(current_key, String.format("%.2f", new_ask));

The following simple test class shows how we can query the MarketIntelligence object to get the ask price for symbol 0001.

class TestMarketIntelligence
    public static void main(String args[]) throws InterruptedException
        MarketIntelligence mi = new MarketIntelligence();
        while( true ){
             String ask = mi.getAsk("0001");

Executing the test module, we can verify that the ask prices are moving up and down and in not too drastic of a rise and fall (so we don’t scare our customers).

trantor:quickfix_demo$ javac -classpath . MarketIntelligence.java
trantor:quickfix_demo$ javac -classpath . TestMarketIntelligence.java
trantor:quickfix_demo$ java -cp . TestMarketIntelligence

While MarketIntelligence is not so intelligent, with a data source for the broker we can now build the broker’s order management system (OMS).  Stay tuned for more updates!

QuickfixJ: Getting started

I’m going to be writing a series of tutorials on using QuickfixJ to implement a simple financial application.  While I hope others can benefit from the tutorial, my primary purpose is so that I can actually get more comfortable with Java after having worked with C++ for my entire career.

QuickfixJ is a Java implementation of the popular open-source Quickfix C++ library that provides a FIX protocol engine for financial applications.  FIX is a simple text-based protocol built on TCP that consists of key-value fields separated by commas, where the keys are numerical indexes that have predefined and user-defined meanings.  There is also an XML version of the protocol, known as FIXML, though it is not utilized in industry as often due to the extra overhead of processing the larger XML messages.

Before we get started with QuickfixJ, we should set up our development environment.  The first step is to do yourself a favor and download Apache Ant.  While you could use makefiles or just build everything from the command line, Ant was made for building Java projects and if you plan to grow your application in any way, Ant will save you a lot of headaches a long the way.  From the Apache Ant project page you can download the libraries as-is and run it on your system.  Install Ant to your system path, and then run the following command to make sure that Ant is in your path and you’re ready to use it:

trantor:Development$ ant -v
Apache Ant version 1.7.1 compiled on October 13 2009
Buildfile: build.xml does not exist!
Build failed

Next, download QuickfixJ from the project website.  After you get everything uncompressed, take a look inside:

trantor:Development$ ls quickfixj/
LICENSE				quickfixj-msg-fix41-1.4.0.jar
bin				quickfixj-msg-fix42-1.4.0.jar
doc				quickfixj-msg-fix43-1.4.0.jar
etc				quickfixj-msg-fix44-1.4.0.jar
lib				quickfixj-msg-fix50-1.4.0.jar
quickfixj-all-1.4.0.jar		quickfixj-msg-fixt11-1.4.0.jar
quickfixj-core-1.4.0.jar	src
quickfixj-examples-1.4.0.jar	src.zip

QuickfixJ supports multiple versions of the FIX protocol, and you can either build with the Java library for your desired version of the protocol, or build with the quickfixj-all library that includes all versions of the protocol. Look in the lib folder too, as it contains the other required libraries.

Finally, lets set up a skeleton Ant build file that we can use to build and run our code later.  If you simply run “ant” in the working directory, it looks for a build.xml file.  We can specify a default target so that when we type “ant” on the command line, it does what we expect, just as we would with makefiles.

<project default="run">
  <path id="project.class.path">
    <!-- QuickfixJ libraries -->
    <pathelement location="/Users/globalengineer/Development/quickfixj/quickfixj-all-1.4.0.jar"/>
    <pathelement location="/Users/globalengineer/Development/quickfixj/lib/slf4j-api-1.5.3.jar"/>
    <pathelement location="/Users/globalengineer/Development/quickfixj/lib/slf4j-jdk14-1.5.3.jar"/>
    <pathelement location="/Users/globalengineer/Development/quickfixj/lib/mina-core-1.1.0.jar"/>
    <!-- Project directory-->
    <pathelement location="."/>

  <target name="compile">
    <javac srcdir=".">
      <classpath refid="project.class.path"/>

  <target name="jar depends="compile">
    <jar destfile="" basedir="." includes="**/*.class">
        <attribute name="Main-Class" value=""/>

  <target name="run" depends="jar">
    <java classname="" fork="true">
      <classpath refid="project.class.path"/>
      <arg value="config.cfg"/>

  <target name="clean">
      <fileset dir="." includes="*.class"/>
      <fileset dir="." includes="*.jar"/>

The Ant build file contains targets for compiling, creating executable jars, running jars, and cleaning up the workspace.  The classpath is specified in a single place so that we can add libraries that can be utilized by both the the compile and run targets.  Stay tuned for future tutorials on using QuickfixJ to implement a financial application.

Boost: Thread timing and timeouts

Boost.Thread has the ability to use timeouts for obtaining mutex resources or even just blocking a thread with the sleep() method.  Creating a timeout is, thankfully, a very easy task. All one needs to know is that the Boost.Thread library takes timeout parameters in the form of boost::system_time (as of Boost 1.35).  This is actually just a simple typedef to a POSIX data structure in the Boost.DateTime library.  From boost/thread/thread_time.hpp:

typedef boost::posix_time::ptime system_time;

To create a simple timeout, the following code will usually suffice:

boost::system_time timeout = boost::get_system_time() + boost::posix_time::milliseconds(n);

The vaule for n is simply an integer value, perhaps randomly generated? There is no need to dig into the large and versatile Boost.DateTime library, and with boost::system_time there is no longer a need to use boost::xtime unless working with an older code base that has yet to be refactored.  With random time period generation and timeouts covered, we are now ready to move onto exploring some multithreaded code.

Boost: a random time period generator

Random numbers play a critical role in the verification of designs, allowing testers to apply stimuli and stress a system beyond the known boundary conditions.  The C++ standard library supplies the random() function, which after seeding, produces a simple pseudo-random sequence.  For many applications, this simple function is enough; alternatively, it is very limiiting if your application needs to grow and support different testing methods.  Though there are many random number libraries freely available, most modern C++ applications utilize Boost, and the Boost libraries contain the Boost.Random library as a compile-only header library.

A glance in the boost/random/ directory can be intimidating at first.  There are various header files with cryptic mathematical names, but at its heart, however, the library is easy to understand once you understand the background concepts and have a statistical reference at your side. There are two key concepts that you need to understand before setting out to use the library: generators and distributions.


Based on the Boost.Random documentation, generators can be classified into roughly three variations:

  • Uniform – number sequences uniformly distributed over a finite range
  • Pseudo – numbers sequences generated by an algorithmic process that simulates random behavior
  • Non-deterministic – number sequences generated by stochastic processes

Determining which type of generator is best for your application depends on many factors, but for most test applications the pseudo-random generator is adequate.  Examples of the pseudo-random generators are minstd_rand and rand48, which are both declared in boost/random/linear_congruential.hpp.  Refer to the boost documentation and header files for more information on the various generators available.

Distributions represent the distribution, or layout, of a sequence of numbers over finite interval based on the corresponding random variable of the same name.  When selecting a distribution for your tests, refer to an undergraduate level Statistics textbook or your favorite statistical reference. Boost.Random supports a large number of statistical distributions, including, but not limited to:

  • Normal
  • Uniform
  • Binomial
  • Exponential
  • Gamma
  • Bernoulli
  • Geometric
  • Poisson

If you need a distribution or generator not included in Boost.Random, you can implement new classes that conform to the Boost.Random interface causing minimal change to your code. More often than not, the library already has a sufficient amount at your disposal.  Popular pseudo-random generators, such as the linear feedback shift that is ubiquitous in hardware engineering (boost/random/linear_feedback_shift.hpp) are available out-of-the-box and ready to use with some simple template parameters at instantiations.

In the remainder of this post, I am going to demonstrate the use of generators and distributions in developing a simple class that generates pseudo-random numbers for time periods.

Generating Random Time Periods

When testing multi-threaded code or even just trying to understand concepts in the Boost.Threads library, I find that having the ability to quickly and easily generate random time intervals beneficial.  One thread can be blocked for X milliseconds, another by Y milliseconds, allowing one to verify the behavior of the various synchronization mechanisms in Boost.Threads.  Using boost::variate_generator, we can bind a generator to a distribution and create a random sequence of numbers representing time periods.  I use a simple class like the RandomTimePeriod class listed below.

#include <boost/random.hpp>
#include <boost/shared_ptr.hpp>

class RandomTimePeriod
  // accept default template param of 'int'
  typedef boost::uniform_int<> distribution_type;
  typedef boost::minstd_rand   generator_type;
  typedef boost::variate_generator< generator_type,
            distribution_type > RandomNumberGenerator;

  RandomTimePeriod(int max_ms=100)
    // Magic number 42 - if you don't understand this,
    //    look into Douglas Adams--now!
    generator_type generator(42);
    distribution_type distribution(0,max_ms);
    _rng.reset(new RandomNumberGenerator(generator, distribution));

  int next()

  boost::shared_ptr _rng;

The code above should be rather straightforward.  Typedefs are used to make the constructor code more readable.  The constructor takes a parameter specifying the max time period in milliseconds, and it constructs the random number generator member variable.  The generator is passed the infamous value of 42 as its seed value, but in real test code one should provide a better method of obtaining a seed.  Calling the next() method on a RandomTimePeriod object will return a pseudo-random number. Internally the random number generator is stored in a smart pointer so that when the object’s reference count reaches zero, the object is properly cleaned up.  Very simple, right?  The following driver program demontrates how to use the RandomTimePeriod class.

int main(int argc, char* argv[])
  RandomTimePeriod rtp;
  for( int i=0; i<25; ++i){
    std::cout << rtp.next() << std::endl;
  return 0;

Armed with a simple random number generator, we can now focus on creating better tests for the verification of our designs.  Stay tuned for more tutorials on Boost libraries, including Boost.Thread.