Saturday, December 3, 2011

QuickFix/J based Fix Protocol enabled trading client


Purpose of this post is to make available a simple sample application for the people who either wants to start learning or want to develop of FIX (FIX protocol) based trading client.

FIX Acceptor ( which acts as the Stock Exchange)
FIX Initiator ( which acts as the Trading Client)

Its just a simple client without any GUI.
People who are already aware about the FIX and just want to try the sample app in java can jump directly to the example, rest of all people can take a pain to read the following:

Some jargons about the FIX protocol:
The Financial Information eXchange ("FIX") Protocol is a series of messaging specifications for the electronic communication of trade-related messages. It has been developed through the collaboration of banks, broker-dealers, exchanges, industry utilities and associations, institutional investors, and information technology providers from around the world. These market participants share a vision of a common, global language for the automated trading of financial instruments ( from Fix Protocol Organization).










Some GYAAN:
If every exchange in the world communicates "ONLY" with their own developed messages (Proprietary Protocol ) than for every exchange there will be need to develop seperately the trading client infrastructure or trading client platform. This is a painful work as to maintain a client with the proprietary messaging or Proprietary Protocol (Message) for every exchange. And keeping the client in the accordance with the exchange notification(s) for upgrades of messages to communicate is a big problem.
And in that case doing a trade with client which supports multiple exchange at the same time seems far from the reality. Of course a client can manage support for few exchange but a large number of exchange will not be possible ( which is the need in the today's world).

With FIX based application its easy to develop OMS ( Order Management System) and EMS ( Execution Management System) faster and scalable. It can be used for Algo Trading but its gonig to be bit slower, so for Algorithmic Trading Proprietary Protocol is a good choice.


A typical FIX message looks like as:
br />
<20111204-11:02:59, FIX.4.2:FixClient8019->FixAcceptor, outgoing>(8=FIX.4.2|9=80|35=A|34=14|49=FixClient8019|52=20111204-11:02:59.353|56=FixAcceptor|98=0|108=60|10=219|)
where every tag has a specific meaning, in the above tags are 8,9,35,34,49,52 etc.

Lets jump to the FIX based Acceptor and Iniator.

FixAcceptor: Which listens on a specific socket and works as a server. It is the Stock Exchange. Number of clients can connect to it. All the properties for the Acceptor is defined in the acceptor.cfg file.
FixInitiator: Which connects to the FixAcceptor on a specific port defined by Acceptor. It is a trading client. Client can connect with different fix implemenation versions which a client and exchange supports. I am using FIX.4.2 version for the example.

Explanation about the .cfg and fix message is beyond the scope of this blog. ha ha ha, i saved some time. Dirty trick to escape but i have no choice as this is a vast subject and neither i have time nor the experities to cover everything.

Create FixAcceptor.java and FixIniator.java either by implementing Application interface or by extending ApplicationAdapter class.

First some snippet from Exchange i.e. FixAcceptor.java

public class FixAcceptor extends MessageCracker implements Application





Start the acceptor based on the configuration defined in acceptor.cfg

SessionSettings settings = new SessionSettings("./conf/acceptor.cfg");

FixAcceptor acceptor = new FixAcceptor();
ScreenLogFactory screenLogFactory = new ScreenLogFactory(settings);
DefaultMessageFactory messageFactory = new DefaultMessageFactory();
FileStoreFactory fileStoreFactory = new FileStoreFactory(settings);
SocketAcceptor socketAcceptor = new SocketAcceptor(acceptor,
fileStoreFactory, settings, screenLogFactory,messageFactory);


socketAcceptor.start();

onMessage(...) : there are many overloaded onMessage() methods are defined in the api, for the purpose of example i have overridden

@Override
public void onMessage(NewOrderSingle order, SessionID sessionID)
 throws FieldNotFound, UnsupportedMessageType, IncorrectTagValue {
...
}
exchange checks for the match for the requested order by the client and in case of match it process the order and updates the client with the execution report. Have a look in the example to see the implementation.



Now some snippet from Trading Client i.e. FixIniator.java
Here i am extending ApplicationAdapter instead of implementing Application as its done in FixAcceptor.java




public class FixInitator extends ApplicationAdapter
Start the initiatorr based on the configuration defined in initiator.cfg
FixInitator fixIniator = new FixInitator();
SessionSettings sessionSettings = new SessionSettings("./conf/initiator.cfg");

ApplicationAdapter application = new FixInitator();
FileStoreFactory fileStoreFactory=new FileStoreFactory(sessionSettings);
ScreenLogFactory screenLogFactory=new ScreenLogFactory(sessionSettings);
DefaultMessageFactory defaultMessageFactory=new DefaultMessageFactory();
fixIniator.socketInitiator = new SocketInitiator(application,
fileStoreFactory, sessionSettings, screenLogFactory,defaultMessageFactory);

fixIniator.socketInitiator.start();

// prepare order NewOrderSingle order = new NewOrderSingle( ...)
try {
// send order to target which is nothing but the exchange/acceptor
    Session.sendToTarget(order, sessionID);
    } catch (SessionNotFound e) {
    e.printStackTrace();
}

I have overridded method fromAdmin(...) where client will receive from the admin where one of the message is the ExecutionReport which is sent by exchange/acceptor.
@Override
public void fromApp(Message message, SessionID sessionId)

COMPLETE EXAMPLE CAN BE DOWNLOADED FROM HERE

Saturday, November 5, 2011

Android App / Mobile Trading Client

My first android app for trading client.
Very happy today, finally i did it, it was long pending task.
I have intention to use QuickFix/J a Fix Protocol based open source library.


For the android app demo purpose (click here to download sample code) i have removed the JMS web service call which can send the order to Fix Protocol based client and just shown the order



                  JMS Web Service                                         Fix Message on TCP/IP To Exchange                            
Mobile Client ===>    JMS Queue  ===> Fix based Client (Broker)   ===>  Fix based Server (Exchange)
                                        QuickFix/J based client Parser
                                     
                                      FROM CLIENT TO BROKER-EXCHANGE DATA FLOW



               Order Status Update (Broadcast-Uni-cast/ TCP-IP Message)
Fix based Server (Exchange)    ===>     Fix based Client (Broker)    ===>   Mobile Client
                                                                                           Order Status Update (may be SMS)


                                      FROM EXCHANGE-BROKER TO CLIENT DATA FLOW


User enters the required Symbol(Script) and other details for Buy/Bid and click on Order button. Android app sends the data to JMS queue which is running on a remote machine at Broker's office and which is based on JMS WebService .

Broker has a Fix protocol based parser running which collects the order from the queue and prepare the Fix based message to Fix protocol based Server, which is located at Stock Exchange.

Once order is confirmed from Exchange the same is sent to Broker and which updates the Client.

Android made the work easy for development, i am not able to find anything much to explain anything in detail. May be have look of the code.

Note: Target audience for this blog and code is only developer and not the android phone user.

Wednesday, September 14, 2011

Remote Debugging In Eclipse

Remote debugging capability with different debuggers( IDEs) are nice features for developers. Purpose of this blog is to share this information that how to use remote debugging tools effectively. Here i tried to give example for eclipse IDE.

Remote debugging in eclipse can be done in two ways:
a) Socket Attach
b) Socket Listen


Socket Attach: For e.g. we want to debug an application which is deployed on tomcat and we want to debug that. Attach the application process through eclipse once we start our tomcat in debug mode.

Step 1:
How to start tomcat in debug mode:
$./catalina.sh jpda start (in case of unix based machines) or
> catalina.bat jpda start ( in case of windows based machines)

This is going to start a tomcat in debug mode and a socket with port as 8000 can be attached to it.
In case if user wants to attach to different port than following can be done.
export JPDA_ADDRESS=8000  (in case of unix based machines)
$./catalina.sh jpda start


set JPDA_ADDRESS=8000 (in case of windows based machines)
> catalina.bat jpda start

Step 2:
Open debug configuration on eclipse and add new Remote Java Application.
Connection Type should be Standard (Socket Attach). Give a host name or ip in the value for Host in connection properties where the remote process is running.
For e.g.

















For Other application server like WebSphere:
Open admin console and open Servers->Server Type -> WebSphere Application Servers.
Than choose your server from the list of available servers. And than select Debugging service.
for e.g:
Application servers > server1 > Debugging service
Make check box "Enable service at server startup" as selected.
default port for debug is 7777, change it if you want to debug on different port.
Restart the server and attach your debugger ( IDE or eclipse) to it.


Socket Listen: When we want to start a listener first and the remote application is required to be attached to the eclipse
debugger, in that case. First we need to start the eclipse debugger in Socket Listten mode and attach the application.

Step 1:
Open debug configuration in eclipse and add new Remote Java Application.
Connection Type should be Standard (Socket Listen).
Port in connection properties should be 8000 if you want remote application should connect using this port value.
For e.g.
















Step 2:
Options a) if wants to debug with ant than in your build.xml add
<jvmarg line="-Xdebug -Xrunjdwp:transport=dt_socket,address=10.240.1.14:8000,server=n" /> for e.g.
<target name="execute" description="Test">
  <java classname="${main.class}" fork="true" failonerror="true">
   <classpath refid="class.path" />
   <arg value="${myargument}" />
   <jvmarg value="${myjvmargument}" />
   <jvmarg value="-Xrs" />
   <jvmarg line="-Xdebug -Xrunjdwp:transport=dt_socket,address=10.240.1.14:8000,server=n" />
  </java>
</target>

     
Option b) If you wants to debug with .bat file or on command prompt

Java -Xdebug -Xrunjdwp:transport=dt_socket,address=10.240.1.14:8000 -jar MyJar.jar


Options c) if you wants to debug a application which is again an eclipse ( or eclipse based plugins) than you can start the eclipse application as


eclipse.exe -vmargs -Dosgi.requiredJavaVersion=1.6 -Xms256m -Xmx512m -Xdebug -Xrunjdwp:transport=dt_socket,address=10.240.1.14:8000,suspend=n

10.240.1.14 IP where you want to debug and where your debugger is running.
Debugging in JBoss can be debugged by modifying JAVA_OPTS in the file which is used to start the server in the similar way as mentioned above.
IBM WebSphere is already explained above.

Friday, June 24, 2011

Dynamic Proxy for gui component listener using InvocationHandler.

Listeners for gui is always easy to create and difficult to maintain.
As they will create additional classes for that and in case we need to
give a patch or something it can be a real pain.

Lets say that a Frame (MyFrame.java) has 10 components and each of them has a listener than there will be 10 additional classes ( MyFrame$1.class,... , MyFrame$10.class, etc).
Now if a fix is given for one of the component and we really do not know which one to give as a hot fix, we will be ending up in giving all the 11 classes.
Another thing which might also force to give all the classes if we change the serialversionId.

So how to overcome this, i have tested it and found it works well.
But is it the right thing to do not sure but good to know.

We can use the InvocationHandler to handle this situation which can call the required method of the frame where we can have the logic/code to be run using Dynamic Proxies to call whenever event is raised.


import java.lang.reflect.*;

/**
 * @author deepak.singhvi
 *
 */
public class InvocationHandlerProxy implements 
      InvocationHandler {

private Object obj;

public static Object newInstance(Object obj) {
  return Proxy.newProxyInstance(obj.getClass()
  .getClassLoader(), obj.getClass().getInterfaces(),
  new InvocationHandlerProxy(obj));
}

public InvocationHandlerProxy(Object obj) {
 this.obj = obj;
}

public Object invoke(Object proxy, Method m, Object[] args)
 throws Throwable {
 Object result;
  try {
    result = m.invoke(obj, args);
  } catch (InvocationTargetException e) {
    throw e.getTargetException();
  } catch (Exception e) {
    throw new RuntimeException("unexpected invocation exception: "
 + e.getMessage());
  } 
  return result;
}
}


For every gui component, for e.g. button instead of overriding actionListener for some action event we can call.

ActionListener foo = (ActionListener) InvocationHandlerProxy.newInstance(new FooWithoutArgActionListener(this,"methodWithoutArgument",new Class[0]));

Listener class would implement ActionListener as usual but the method to be called when a
specific event is raised will be defined in the same class where listener is created, without creating lister anonymously.

public class FooWithoutArgActionListener 
implements ActionListener {
  Method method;
  Object parent;
  public FooWithoutArgActionListener(Object classObject, 
    String methodName, Class[] parameterTypes ){
    method = getTargetMethod(classObject, methodName, parameterTypes);
    this.parent = classObject;
}

@Override
public void actionPerformed(ActionEvent e) {
 ....
  method.invoke(parent, new Object[0]);
 ...
}

private Method getTargetMethod(Object target,
  String methodName, Class[] parameter) 
{
// find the target method which should get 
// executed when actionPerformed is called.
}


Click here to get the Complete example

Saturday, June 4, 2011

Find from which jar a class was loaded

In order to find at runtime where from file system a class was loaded, following command would be useful:

System.out.println(<myjavaclassname>.class.getProtectionDomain().getCodeSource().getLocation());

Output will be something like this:
file:/C:/TestWorkSpace/lib/MyLibrary.jar

It can be helpful while debugging some class loading problems.

Friday, March 11, 2011

Hibernate and DAO

UNDER CONSTRUCTION


package com.dao;

public interface DAOIntf<T> {
public void update(T obj);
public void save(T obj);
public void delete(T obj);
}





package com.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.util.HibernateUtil;



public class AbstractDAOImpl<T> implements DAOIntf<T>{

  @Override
  public void update(T obj) {
    save(obj);
  }

  @Override
  public void save(T obj) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();
      session.save(obj);
      transaction.commit();
    } catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
  }

  @Override
  public void delete(T obj) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();
      session.delete(obj);
      transaction.commit();
    } catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
  
   }

}



ProductDAOIntf.java
package com.dao;

import java.util.List;

public interface ProductDAOIntf<T> extends DAOIntf<T> {
  public T getProductByID(int id);
  public List<T> getAllProducts();
}


ProductDAOImpl.java
package com.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.hbm.Product;
import com.util.HibernateUtil;



public class ProductDAOImpl<T> extends AbstractDAOImpl<T> implements ProductDAOIntf<T> {

  @Override
  public T getProductByID(int id) {
  Session session = HibernateUtil.getSessionFactory().openSession();
    T product=null;
    try {
      product =(T) session.get(Product.class,id);  
    } catch (HibernateException e) {
      e.printStackTrace();
    } finally {
      session.close();
    }
    return product;
  }
 
  @Override
    public List<T> getAllProducts(){
    Session session = HibernateUtil.getSessionFactory().openSession();
    List<T> list = null;
    try {
      list = session.createQuery("from Product").list();
    } catch (HibernateException e) {
      e.printStackTrace();
    } finally {
      session.close();
    }
    return list;
  }

}


Product.java
package com.hbm;

import java.io.Serializable;

public class Product implements Serializable {
 
 
  public Integer getProduct_Id() {
    return Product_Id;
  }

  public void setProduct_Id(Integer product_Id) {
    Product_Id = product_Id;
  }

  public String getProduct_Name() {
    return Product_Name;
  }

  public void setProduct_Name(String product_Name) {
    Product_Name = product_Name;
  }

  public Double getProduct_Price() {
    return Product_Price;
  }

  public void setProduct_Price(Double product_Price) {
    Product_Price = product_Price;
  }

  public Integer getProduct_QOH() {
    return Product_QOH;
  }

  public void setProduct_QOH(Integer product_QOH) {
    Product_QOH = product_QOH;
  }

  Integer Product_Id;
  String Product_Name;
  Double Product_Price;
  Integer Product_QOH;

  @Override
    public String toString() {
      return "Id : " + Product_Id + "\t Name " + Product_Name + "\tQOH " + Product_QOH;
    }
}

Product.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

  <class name="com.hbm.Product" table="product" >
   <id name="Product_Id" type="int"> <generator class="identity"></generator></id>
   <property name="Product_Name" type="string" length="50" />
   <property name="Product_Price" type="double" lazy="true" />
   <property name="Product_QOH" type="int"/>
   
  </class>
</hibernate-mapping>