Placing Trades with Interactive Brokers using the SumZero Trading API

Placing trades through Interactive Brokers using the SumZero Trading API is a relatively straightforward task, with support for Equity, Futures, and Foreign Exchange orders.  A few examples are below that illustrate how to place orders for the various markets as well as screenshots of Interactive Brokers Trader Workstation (TWS), which is their desktop trading client.  The API interacts with Trader Workstation, and when a trade is placed via the API, the trade will then appear in Trader Workstation where it is routed to Interactive Brokers, and then on to its specified exchange.


Equity Order

In the equity order example below, a connection to the Interactive Brokers client is obtained, which is running on the localhost at port 7999.

A StockTicker object is constructed for Amazon (ticker AMZN), the SumZero library initializes default properties for the ticker such as which exchange to route to.

The next order ID is obtained from the broker, and a TradeOrder object is constructed, specifying the orderId, the ticker symbol for the order, the number of shares, and whether this is a buy or sell order.

The order is then placed with the Interactive Brokers client.

If no other parameters are specified on the order, it is assumed to be a market order which will be placed in the market immediately after it is passed to the broker.

In the example below, we are placing a market order to sell 500 shares of Amazon.

public void placeEquityOrder() {
InteractiveBrokersClientInterface ibClient = InteractiveBrokersClient.getInstance("localhost", 7999, 1);
StockTicker amazonTicker = new StockTicker("AMZN");
String orderId = ibClient.getNextOrderId();
int shares = 500;
TradeOrder order = new TradeOrder(orderId, amazonTicker, shares, TradeDirection.SELL);

view raw

hosted with ❤ by GitHub


Below is a screen shot of Interactive Brokers Trader Workstation.  There is a line with price information for Amazon stock (AMZN), showing a bid price of $559.02 and an ask of $559.80.  In the line immediately below, the order is visible which was placed by the code above.  A market order to sell 500 shares of Amazon.




Futures Order

Submitting orders for the futures markets is very similar to the equity markets, except a few more parameters need to be specified when building a ticker, such as what month and year that desired futures contract is expiring.

In the example below, we build a new FuturesTicker object for crude oil, specifying the symbol “CL”, and a contract expiration of April 2016.  Also, the exchange needs to be specified for futures, which in this case is NYMEX.

From this point on, the order process is exactly the same as the previous example.  This time however, we’ll place a limit order to buy 5 contracts at $32.50, meaning that the price needs to come down to at least $32.50 for the trade to be executed.

public void placeFuturesOrder() {
InteractiveBrokersClientInterface ibClient = InteractiveBrokersClient.getInstance("localhost", 7999, 1);
//Create a crude oil futures ticker
FuturesTicker futuresTicker = new FuturesTicker();
String orderId = ibClient.getNextOrderId();
int contracts = 5;
//Create the order and send to Interactive Brokers
TradeOrder order = new TradeOrder(orderId, futuresTicker, contracts, TradeDirection.BUY);


The result of the example is illustrated in the screenshot of TWS below.  There is a line corresponding to April 2016 Crude Oil, (CL Apr’16 @NYMEX), which shows a bid price of $33.22 and ask of $33.23.  On the line immediately below, the order that was submitted by the program above is shown.  Buy 5 contracts at a limit price of $32.50.



Foreign Exchange Order

Finally, in the last example I’ll show how to place an order for foreign currencies through the API.

Again, the general process is the same as above, in this example we’ll construct an order to buy 50,000 Euros.

The symbol for the currency ticker is “EUR”, and the underlying currency needs to be set to “USD”.  The exchange where currency trades are executed at Interactive Brokers is “IDEALPRO”.  The amount of the order is set to 50000, and the TradeOrder object is constructed to buy at the market price.

public void placeCurrencyOrder() {
InteractiveBrokersClientInterface ibClient = InteractiveBrokersClient.getInstance("localhost", 7999, 1);
CurrencyTicker eurTicker = new CurrencyTicker();
String orderId = ibClient.getNextOrderId();
int amount = 50000;
TradeOrder order = new TradeOrder(orderId, eurTicker, amount, TradeDirection.BUY);

view raw

hosted with ❤ by GitHub



The TWS screenshot below shows the EUR row denoted by “EUR.USD”, with a bid and ask price of $1.08695.  The row immediately below shows our order to buy 50,000 EUR at the market price, routed to IDEALPRO



These were some simple examples of various order types that can be submitted to buy/sell equities, futures, and currencies at Interactive Brokers.  More complex order types such as OCO, OSO, FOK, MOC, etc. are possible with the SumZero API, and will be shown in future posts.

twitter: @RobTerpilowski
twitter: @SumZeroTrading
LinkedIn: Rob Terpilowski




3 thoughts on “Placing Trades with Interactive Brokers using the SumZero Trading API

  1. Hi Rob,
    I really like your SumZero Trading API. I think that the original IB API is too complicated and additional layer is a very good idea. I’m looking last 2 weeks for a better solution to connect my trading forex strategies to Interactive brokers then NinjaTrader – very limited, many issues, not reliable, complicated development and strategies management.

    Just few questions…maybe I’m just blind, but I couldn’t find way how to:
    1) get all currently open positions
    2) get all closed positions / closed trades or some history of my trading
    Do you have these methods in your API? Are you planning to implement it?


  2. Hi Tomas,

    Yes, I am planning on implementing functionality to get all currently open positions, as well as currently open orders.

    The closed positions / closed trades / history is a bit trickier. The TWS API doesn’t have functionality to get trade executions that are older than the current day, *unless* you open TWS itself, select “Trade History”, and select ‘show trades for 7 days’, at that point, API apps have access to 7 days worth of executions from TWS. If you are connecting an API app to the IB Gateway instead of TWS, I believe you are limited to the current day’s executions.

    The other possible better/more-reliable option would be to integrate the app with the IB web services in order to retrieve execution reports, although I haven’t investigated if a custom report would need to be created or if one of the existing ones in the account management site would work. Still thinking about the best way to implement this functionality.

    The functionality that I am working on at the moment is to get a list of all open orders that were placed by the API app in the event that the app has been closed down after placing an order.

    • Hi Rob,
      perfect I will wait for this feature. Actually I need closed positions history and all open orders just for case the trading app lose connection to IB or crashes. It’s already happened to me few times (with NinjaTrader). One day is totally fine for that. I’m using DB for storing the strategy positions data anyway so long term order history is not necessary.
      However you can create a Flex Query in Account Management to get older trades in structured CSV. It should be possible to access these queries over WebServices, but I don’t have experience with that.

Leave a Reply