Request IB Tick Data - JAVA API

Discussion in 'Data Sets and Feeds' started by BayStFXTrader, Sep 6, 2010.

  1. Hi,

    I'm a newbie with Interactive Brokers and I see from the posts that some of you have had quite some experience with their platform.

    I was trying to implement my Strategy with Interactive brokers using their Java API. Unfortunately, I'm not quite sure what the error is below. I want to be able to place Forex and Futures Trades. However, right now, I cannot even receive a Quote for Java.

    My code is below.

    Code:
     PrintWrapper wrapper = new PrintWrapper();
            EClientSocket client = new EClientSocket(wrapper);
            int clientId = 1;
            client.eConnect("127.0.0.1", 7496, clientId);
            Contract con = new Contract();
            con.m_localSymbol = "EUR";
            con.m_symbol = "EUR";
            con.m_currency = "USD";
            con.m_exchange = "IDEALPRO";
            con.m_secType = "CASH";
            int tickerId = 100001;
            System.out.println("PLEASE GIVE ME MARKET DATA");
            client.reqMktData(tickerId, con, "", true);
            
            
            System.out.println("Sample TWS API Client Java code to print market data");
            System.out.println("getting quotes for AAPL STK");
            System.out.println("Press CTRL-C to quit");
            Contract contract = new Contract();
            contract.m_symbol="AAPL";
            contract.m_secType="STK";
            contract.m_exchange="SMART";
            //contract.expiry="200303";
            tickerId = 10002;
            client.reqMktData(tickerId,contract, "", true);
            Thread.yield();
            
    

    The output I get is below. Can anyone please help me with this?


    Server Version:49
    TWS Time at connection:20100906 23:54:17 EST
    PLEASE GIVE ME MARKET DATA
    nextValidId: 100023
    Sample TWS API Client Java code to print market data
    getting quotes for AAPL STK
    Press CTRL-C to quit


    Thanks in advance.
     
  2. promagma

    promagma

    Close - but your class must implement EWrapper and create client object with "this" instead of some random PrintWrapper.
    You get your quotes in the tickPrice callback funtion.
    I hacked this together so it won't compile but here is the structure.

    Code:
    public class InterfaceIB implements EWrapper
    {
       EClientSocket client = new EClientSocket(this);
    
       public InterfaceIB()
       {
            int clientId = 1;
            client.eConnect("127.0.0.1", 7496, clientId);
            Contract con = new Contract();
            con.m_localSymbol = "EUR";
            con.m_symbol = "EUR";
            con.m_currency = "USD";
            con.m_exchange = "IDEALPRO";
            con.m_secType = "CASH";
            int tickerId = 100001;
            System.out.println("PLEASE GIVE ME MARKET DATA");
            client.reqMktData(tickerId, con, "", true);
            
            
            System.out.println("Sample TWS API Client Java code to print market data");
            System.out.println("getting quotes for AAPL STK");
            System.out.println("Press CTRL-C to quit");
            Contract contract = new Contract();
            contract.m_symbol="AAPL";
            contract.m_secType="STK";
            contract.m_exchange="SMART";
            //contract.expiry="200303";
            tickerId = 10002;
            client.reqMktData(tickerId,contract, "", true);
            Thread.yield();
       }
    
      public void tickPrice(int tickerId, int field, double price, int canAutoExecute)
      {
        try
        {
        		if (field == TickType.BID)
        			System.out.println("Holy cow this is working, I got bid " + (float)price);
        		else if (field == TickType.ASK)
        			System.out.println("Holy cow this is working, I got ask " + (float)price);
        		else if (field == TickType.LAST)
        			System.out.println("Holy cow this is working, I got last " + (float)price);
        }
        catch(Exception e)
        {
          // If you want to see any crashes you must do your own error handling in callback functions
        }
    }
    
    // For it to compile, you need dummy implementions for a bunch of callback functions that you don't care about.
    // Here are a few, but there are probably more.
    
        public void updateNewsBulletin( int msgId, int msgType, String message, String origExchange) { }
    
        public void managedAccounts( String accountsList) { }
    
        public void receiveFA(int faDataType, String xml) { }
        
        public void updateAccountTime(String timeStamp) { }
        
        public void updatePortfolio(Contract contract, int position, double marketPrice,
        		double marketValue, double averageCost, double unrealizedPNL, double realizedPNL,
        		String accountName) { }
    
        public void updateMktDepth( int tickerId, int position, int operation,
                int side, double price, int size) { }
    
    	public void updateMktDepthL2( int tickerId, int position, String marketMaker,
    	                int operation, int side, double price, int size) { }
    	
        public void scannerData(int reqId, int rank, ContractDetails contractDetails, String distance, String benchmark, String projection) { }
    
        public void scannerParameters(String xml) { }
        
        public void bondContractDetails(ContractDetails contractDetails) { }
        
        public void tickSize( int tickerId, int field, int size) { }
        
        public void openOrder(int orderId, Contract contract, Order order, OrderState orderState) { }
        
        public void tickString(int tickerId, int tickType, String value) { }
        
        public void tickGeneric(int tickerId, int tickType, double value) { }
        
        public void tickEFP(int tickerId, int tickType, double basisPoints,
    			String formattedBasisPoints, double impliedFuture, int holdDays,
    			String futureExpiry, double dividendImpact, double dividendsToExpiry) { }
    
        public void scannerData(int reqId, int rank, ContractDetails contractDetails, String distance,
        		String benchmark, String projection, String legsStr) { }
    
        public void scannerDataEnd(int reqId) { }
        
        public void currentTime(long time) { }
        
        public void realtimeBar(int reqId, long time, double open, double high, double low, double close, long volume, double wap, int count) { }
        
        public void tickOptionComputation(int tickerId, int field, double impliedVol, double delta, double modelPrice, double pvDividend) { }
    
    }
    
     
  3. Thanks a lot for your help Promagma

    I understand what your saying. However, I already have a implemented a PrintWrapper class and its doing exactly what you have suggessted.

    I'm not sure what's the difference? My PrintWrapper Class is given below.


    Code:
    import com.ib.client.EWrapper;
    import com.ib.client.Execution;
    import com.ib.client.Contract;
    import com.ib.client.ContractDetails;
    import com.ib.client.UnderComp;
    import com.ib.client.Order;
    import com.ib.client.OrderState;
    
    /**
     * Prints all events
     */
    public class PrintWrapper implements EWrapper {
    
       /* ***************************************************************
        * AnyWrapper
        *****************************************************************/
    
       public void error(Exception e) {
          System.out.println(e);
       }
    
       public void error(String str) {
          System.out.println(str);
       }
    
       public void error(int id, int errorCode, String errorMsg) {
          System.out.println("error: id = " + id + ", code = " + errorCode + ", msg = " + errorMsg);
       }
    
       public void connectionClosed() {
          System.out.println("--------------------- CLOSED ---------------------");
       }
    
       /* ***************************************************************
        * EWrapper
        *****************************************************************/
    
       public void tickPrice(int tickerId, int field, double price, int canAutoExecute) 
       {
    	   try
    	    {
    		   System.out.println(" Price Fundtion - tickPrice: tickerId = "+tickerId+", field = "+field+", price = "+price);
    	    }
    	    catch(Exception e)
    	    {
    	      System.out.println("ERROR in TickPrice: "  + e);
    	    }
         
       }
    
       public void tickSize(int tickerId, int field, int size) {
          System.out.println("Size Fundtion - tickSize: tickerId = "+tickerId+", field = "+field+", size = "+size);
       }
    
       public void tickGeneric(int tickerId, int tickType, double value) 
       { String toBeReturned = "Ticker ID = " + tickerId + "\n";
          toBeReturned += "Tick Type = " + tickType + "\n";
          toBeReturned += "Value = " + value + "\n";
          System.out.println(toBeReturned);
       }
    
       public void tickString(int tickerId, int tickType, String value)
       {  String toBeReturned = "Ticker ID = " + tickerId + "\n";
    	  toBeReturned += "Tick Type = " + tickType + "\n";
    	  toBeReturned += "Value = " + value + "\n";
    	  System.out.println(toBeReturned);
       }
    
       public void tickSnapshotEnd(int tickerId) 
       { String toBeReturned = "Ticker ID = " + tickerId + "\n";
         System.out.println(toBeReturned);
       }
    
       public void tickOptionComputation(int tickerId, int field, double impliedVol,
          double delta, double modelPrice, double pvDividend) {
          System.out.println("tickOptionComputation");
       }
    
       public void tickEFP(int tickerId, int tickType, double basisPoints, String formattedBasisPoints, double impliedFuture, int holdDays,
                           String futureExpiry, double dividendImpact, double dividendsToExpiry)
       {  String toBeReturned = "Ticker ID = " + tickerId + "\n";
    	      toBeReturned += "Tick Type = " + tickType + "\n";
    	      toBeReturned += "Basis Points = " + basisPoints + "\n";
    	      toBeReturned += "Formatted Basis Points = " + formattedBasisPoints + "\n";
    	      toBeReturned += "Implied Future = " + impliedFuture + "\n";
    	      toBeReturned += "Hold Days = " + holdDays + "\n";
    	      toBeReturned += "Future Expiry = " + futureExpiry + "\n";
    	      toBeReturned += "Dividend Impact = " + dividendImpact + "\n";
    	      toBeReturned += "Dividends to Expiry = " + dividendsToExpiry + "\n";
    	      System.out.println(toBeReturned);
    	      
       }
    
       public void orderStatus(int orderId, String status, int filled, int remaining, double avgFillPrice, int permId, int parentId, 
    		   double lastFillPrice, int clientId, String whyHeld) 
       {   String toBeReturned = "Client ID = " + clientId + "\n";
    	          toBeReturned += "Order ID = " + orderId + "\n";
                  toBeReturned += "Status := " + status + "\n";
                  toBeReturned += "Filled = " + filled + "\n";
                  toBeReturned += "Remaining = " + remaining + "\n";
                  toBeReturned += "Avg. Fill Price = " + avgFillPrice + "\n";
                  toBeReturned += "Perm ID = " + permId + "\n";
                  toBeReturned += "Parent ID = " + parentId + "\n";
                  toBeReturned += "Last Fill Price = " + lastFillPrice+ "\n";
                  toBeReturned += "HELD ?? = " + whyHeld + "\n";
            System.out.println(toBeReturned);
       }
    
       public void openOrder(int orderId, Contract contract, Order order, OrderState orderState) {
          System.out.println("openOrder");
       }
    
       public void openOrderEnd() {
          System.out.println("openOrderEnd");
       }
    
       public void updateAccountValue(String key, String value, String currency, String accountName) {
          System.out.println("updateAccountValue");
       }
    
       public void updatePortfolio(Contract contract, int position, double marketPrice, double marketValue,
          double averageCost, double unrealizedPNL, double realizedPNL, String accountName) {
          System.out.println("updatePortfolio");
       }
    
       public void updateAccountTime(String timeStamp) {
          System.out.println("updateAccountTime: " + timeStamp);
       }
    
       public void accountDownloadEnd(String accountName) {
          System.out.println("accountDownloadEnd");
       }
    
       public void nextValidId(int orderId) {
          System.out.println("nextValidId: " + orderId);
       }
    
       public void contractDetails(int reqId, ContractDetails contractDetails) {
          System.out.println("contractDetails");
       }
    
       public void contractDetailsEnd(int reqId) {
          System.out.println("contractDetailsEnd");
       }
    
       public void bondContractDetails(int reqId, ContractDetails contractDetails) {
          System.out.println("bondContractDetails");
       }
    
       public void execDetails(int reqId, Contract contract, Execution execution) {
          System.out.println("execDetails");
       }
    
       public void execDetailsEnd(int reqId) {
          System.out.println("execDetailsEnd");
       }
    
       public void updateMktDepth(int tickerId, int position, int operation, int side, double price, int size) {
          System.out.println("updateMktDepth");
       }
    
       public void updateMktDepthL2(int tickerId, int position, String marketMaker, int operation,
          int side, double price, int size) {
          System.out.println("updateMktDepthL2");
       }
    
       public void updateNewsBulletin(int msgId, int msgType, String message, String origExchange) {
          System.out.println("updateNewsBulletin");
       }
    
       public void managedAccounts(String accountsList) {
          System.out.println("managedAccounts");
       }
    
       public void receiveFA(int faDataType, String xml) {
          System.out.println("receiveFA");
       }
    
       public void historicalData(int reqId, String date, double open, double high, double low,
          double close, int volume, int count, double WAP, boolean hasGaps) {
    	   //logIn("historicalData, "+reqId+" , "+date+" , "+open+" , "+close+" , hasgaps: , "+hasGaps);
       }
    
       public void scannerParameters(String xml) {
          System.out.println("scannerParameters");
       }
    
       public void scannerData(int reqId, int rank, ContractDetails contractDetails, String distance,
          String benchmark, String projection, String legsStr) {
          System.out.println("scannerData");
       }af
    
       public void scannerDataEnd(int reqId) {
          System.out.println("scannerDataEnd");
       }
    
       public void realtimeBar(int reqId, long time, double open, double high, double low, double close,
          long volume, double wap, int count) {
          System.out.println("realtimeBar");
       }
    
       public void currentTime(long millis) {
          System.out.println("currentTime");
       }
    
       public void fundamentalData(int reqId, String data) {
          System.out.println("fundamentalData");
       }
    
       public void deltaNeutralValidation(int reqId, UnderComp underComp) {
          System.out.println("deltaNeutralValidation");
       }
    
    }
    
    

    And after having that, I just use the following class to see if I can print a forex quote.

    Code:
    public class PrintTestForex {
        public static void main(String[] args) {
            PrintWrapper wrapper = new PrintWrapper();
            EClientSocket client = new EClientSocket(wrapper);
            int clientId = 1;
            client.eConnect("", 7496, clientId);
            Contract con = new Contract();
            con.m_symbol = "EUR";
            con.m_localSymbol = "EUR";
            con.m_currency = "USD";
            con.m_exchange = "IDEALPRO";
            con.m_secType = "CASH";
            int tickerId = 001;//System.currentTimeMillis()/1000;
            client.reqMktData(tickerId, con, "", true);
            System.out.println("Now Placing A Buy Order :" + con.m_localSymbol + "." + con.m_currency);
            Order ord = new Order();
            ord.m_totalQuantity = 20000;
            tickerId++;
            ord.m_orderId = tickerId;
            ord.m_action = "BUY";
            ord.m_orderType = "MKT";
            ord.m_lmtPrice = 0.0;
            client.placeOrder(tickerId, con, ord); System.out.println();
            try {Thread.sleep(50);} catch (Exception e) {}
            
    //        System.out.println("Now Placing A Sell Order :" + con.m_localSymbol + "." + con.m_currency);
    //        ord.m_totalQuantity = 15000;
    //        ord.m_action = "SELL";
    //        tickerId++;
    //        ord.m_orderId = tickerId;
    //        client.placeOrder(tickerId, con, ord); System.out.println();
    //        try {Thread.sleep(50);} catch (Exception e) {}
    //        System.out.println("Now Exiting the System");
            System.exit(1);
            
        }
    
    }
    
    So I'm not sure where the difference is ?
     
  4. promagma

    promagma

    Ah yeah you got it right....

    Well the IB API is a delicate beast :)
    So looking at my own working application, I see two differences in our code.

    When adding a stock I am setting
    thisContract.m_currency = "USD";

    When adding forex I do not have this line
    thisContract.m_localSymbol = "EUR";
     
  5. Well, I'm not sure if it has much to do with local symbol. For example,

    When I leave the m_localsymbol empty, I get the output below

    Code:
    Contract con = new Contract();
            con.m_localSymbol = "";
            con.m_symbol = "EUR";
            con.m_currency = "USD";
            con.m_exchange = "IDEALPRO";
            con.m_secType = "CASH";
            int tickerId = 100000;
            client.reqMktData(tickerId, con, "", false);
           
    
    Server Version:49
    TWS Time at connection:20100907 17:03:24 EST
    nextValidId



    On the other hand when I leave m_localSymbol filled, the output is below

    Code:
    Contract con = new Contract();
            con.m_localSymbol = "EUR";
            con.m_symbol = "";
            con.m_currency = "USD";
            con.m_exchange = "IDEALPRO";
            con.m_secType = "CASH";
            int tickerId = 100000;
            client.reqMktData(tickerId, con, "", false);
    
    Server Version:49
    Server Version:49
    TWS Time at connection:20100907 17:09:55 EST
    nextValidId



    Now if I leave both of them filled the output becomes the following.

    Code:
            Contract con = new Contract();
            con.m_localSymbol = "EUR";
            con.m_symbol = "EUR";
            con.m_currency = "USD";
            con.m_exchange = "IDEALPRO";
            con.m_secType = "CASH";
            int tickerId = 100000;
            client.reqMktData(tickerId, con, "", false);
    
    Server Version:49
    TWS Time at connection:20100907 17:12:38 EST
    nextValidId


    GOD, this experience with IB is soooo miserable. On top of that their Technical Assistance guy on chat never came. One of them came online, but after saying 'HI', he never responded.

    I wonder if everybody's first expereience with IB was the same
     
  6. There is a Yahoo TWS API group ... join it and see there are lots of sample code postings there. People will answer questions too.
     
  7. Tried it. No Help so far.

    :(

    I guess its just one of those days.......
     
  8. promagma

    promagma

    I hear yah ..... try removing the local symbol line altogether. It may treat null and blank differently.
    Other than that I dunno - your code looks the same as mine.
     
  9. LMAO

    MY friend, I don't know how you came up withat and what's the justification for it, but it works...



    Code:
      client.eConnect("", 7496, clientId);
            Contract con = new Contract();
            con.m_symbol = "EUR";
            con.m_currency = "USD";
            con.m_exchange = "IDEALPRO";
            con.m_secType = "CASH";
            int tickerId = (int)System.currentTimeMillis()/1000;
            client.reqMktData(tickerId, con, "100,101,104,106,162,165,221,225", true);
    

    Server Version:49
    TWS Time at connection:20100907 18:23:46 EST
    nextValidId: 100038
    Now Placing A Buy Order :null.USD

    openOrderEnd
    error: id = -1, code = 2104, msg = Market data farm connection is OK:usfuture
    error: id = -1, code = 2104, msg = Market data farm connection is OK:cashfarm
    error: id = -1, code = 2104, msg = Market data farm connection is OK:usfarm
    error: id = -296996, code = 103, msg = Duplicate order id
    Price Fundtion - tickPrice: tickerId = -296998, field = 9, price = 1.2682
    Price Fundtion - tickPrice: tickerId = -296998, field = 1, price = 1.26815
    Size Fundtion - tickSize: tickerId = -296998, field = 0, size = 1500000
    Price Fundtion - tickPrice: tickerId = -296998, field = 2, price = 1.26825
    Size Fundtion - tickSize: tickerId = -296998, field = 3, size = 1500000



    Now all I gotta do is figure out how to separate bid and ask price and size, respectively..... I hope its not another struggle.

    Any tips will be much appreciated.
     
  10. promagma

    promagma

    haha it was a wild guess - the IB API is a funny thing :)
    The rest is easy.

    Code:
        		if (field == TickType.BID)
        			System.out.println("Holy cow this is working, I got bid " + (float)price);
        		else if (field == TickType.ASK)
        			System.out.println("Holy cow this is working, I got ask " + (float)price);
        		else if (field == TickType.LAST)
        			System.out.println("Holy cow this is working, I got last " + (float)price);
    
     
    #10     Sep 7, 2010