Connecting to Interactive Brokers to receive streaming real-time market data is easy with the SumZero Trading API. This example will illustrate how to connect to an Interactive Brokers TraderWorkstation (TWS) or IB Gateway instance in order to obtain quotes for Amazon.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.sumzerotrading.data.StockTicker; | |
import com.zerosumtrading.interactive.brokers.client.InteractiveBrokersClient; | |
import com.sumzerotrading.marketdata.ILevel1Quote; | |
import com.sumzerotrading.marketdata.QuoteType; | |
public class MarketDataStocksExample { | |
public void start() { | |
InteractiveBrokersClient ibClient = new InteractiveBrokersClient("localhost", 6468, 1); | |
ibClient.connect(); | |
StockTicker stockTicker= new StockTicker("AMZN"); | |
ibClient.subscribeLevel1(stockTicker, (ILevel1Quote quote) -> { | |
if( quote.getType().equals(QuoteType.LAST) ){ | |
System.out.println("Received Quote: " + quote.getValue() ); | |
} | |
}); | |
} | |
public static void main(String[] args) { | |
new MarketDataStocksExample().start(); | |
} | |
} |
The first step is to create a new InteractiveBrokersClient object passing in the hostname that TWS or IB Gateway is running on, the port that is listening on, as well as a client ID for the connection. All connections to Interactive Brokers require a client ID which must be unique for each application that connects via the API.
Once the connection is established a new StockTicker object is created which will be used to subscribe to market data for Amazon (AMZN). In order to subscribe to market data the subscribeLevel1() method needs to be called on the client object and passed a Level1Listener object. In this case a lambda expression is passed in which will check the type of Level1Quote that was received, and if the quote was a ‘Last’ price, as opposed to a bid or ask, then print the value of that price to the console.
For this example I’ve connected to the special Interactive Brokers “edemo” account which is free to use, but provides fictitious data for its data feed. It is a good account to test with to make sure that an application is connecting and receiving data as expected.
The output of the example application which was running within NetBeans IDE appears below.
SumZero API Github project page
twitter: @RobTerpilowski
twitter: @ZeroSumTrading