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.


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.


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.



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





Subscribing to Real-Time Market Data With Interactive Brokers Using the SumZero Trading API

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.

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.

Screen Shot 2016-02-08 at 7.22.31 AM

SumZero API Github project page

twitter: @RobTerpilowski
twitter: @ZeroSumTrading

Developing Trading Applications with the SumZero Trading API

I have open sourced a Java trading library which I have been using to develop automated trading applications for many years.  The SumZero Trading API provides the ability to develop trading applications for the equity, futures, and currency markets, by utilizing the following sub APIs

  • Market Data API – Request real time Level 1 (NBBO) and Level 2 (Market Depth) market data
  • Broker API – Submit, execute, and monitor orders
  • Historical Data API – Request intraday and end-of-day historical market data.
  • Strategy API – Develop trading strategies to automatically place buy/sell orders based on user defined algorithms.

The library includes implementation of all of these APIs for Interactive Brokers, except for the Broker API, which also has an implementation for Quantitative Brokers.

The libraries are licensed under the MIT open source license and source code is available at:

In future posts I will show how easy it is to connect to Interactive Brokers to request real-time market data and place a trade using the API.

twitter: @RobTerpilowski
twitter: @SumZeroTrading

Article in Futures Magazine on our Commodity Trading Program

From the December 2014 issue of Futures Magazine • Subscribe!

Zoi: A match made in cyber heaven

Konstantinos (Gus) Tsahas and Robert Terpilowski had similar ideas regarding trading. These partners, who have been working on trading strategies together for nearly a decade, met of all places on an Interactive Brokers (IB) message board where they began sharing ideas (both have an engineering background) despite being on separate coasts: Tsahas in New York and Terpilowski in Seattle.

“Around 2000, Interactive Brokers offered an API and I began developing a mean reversion strategy for the equity markets,” Terpilowski says. “I was working on software to automate that. Gus actually posted something on the message board of the API group so we hooked up and started bouncing ideas off of each other and hit it off.”

Tsahas adds, “It just turned out that we were working on the same mean reversion ideas. I was further along in some aspects, Rob was [further along] in others. Collaborating helped both of us to come up with some good strategies. That was the start.”

This collaboration continued for five years with both Terpilowski and Tsahas pursuing separate careers: Terpilowski in various software engineering positions and Tsahas running his own business installing fiber optic lines.

By 2005 they were trading a number of different strategies but running into scalability issues trading individual equities and decided to look at taking their mean reverting strategies and porting them over to futures.

“We noticed in 2005 that it was difficult to get filled in equity markets,” Tsahas says.

“The reason we chose the mean reversion strategies is we were looking at forming a CTA and felt like mean reversion was a pretty good alternative to the 70% or so of [CTAs] who were trend followers,” Terpilowski says. “That would allow people to include our strategy in their portfolio and provide a return stream that was uncorrelated to other CTAs.”

At the time Tsahas went back to school to get a financial engineering degree and entered an IB-sponsored trading contest using their methodology. “I actually came in second place using this strategy and won $50,000.”

Both would build and code the strategy. “Once we hit something that was beneficial we would share it. It was a lot of test and verify,” Tsahas says. “That is the beauty of having a second person with a different set of skills. Once I saw something that I liked or Rob saw something that he liked, we would port it over and test it ourselves.”

“That is one of the reasons we have worked so well together,” Terpilowski adds. “Being from an engineering background we basically say if it is not something that we can model and backtest it is not something that we are willing to trade.”

By 2007 they began trading proprietary money on 19 futures markets in six sectors. Their strategy attempts to capture short-term pullbacks in medium-term (two to three-week) trends.  They did not attempt to optimize their strategy on each market but rather on the entire portfolio to avoid curve-fitting.

“The inputs we use for natural gas are the same inputs that we use for the S&P 500 or gold or wheat,” Terpilowski says. “We wanted to avoid curve-fitting so we decided we are going to optimize it at the portfolio level only and we included 40 markets.”

Their strategies performed extremely well in 2007-2009 and by 2010 they began trading customer money in CTA Zoi Capital.

Winning trades typically last 1.5 days, with losers lasting 2.5 days. Zoi’s Telio program has a four-point risk management strategy. They exit the market in five days if a trade does not begin to revert back to the mean.

“We want to minimize the amount of time in the market because whenever you are in the market you are assuming risk,” Terpilowski says. “We apply stop losses whenever we open a new position but they are dynamic; if volatility is higher we want to place the stops a little further away than if volatility is less to give it more room to breathe.”

However, Zoi will reduce the position size when applying wider stops. That way they maintain their risk parameters, 2.5% on every trade, but allow trades to work. They also will exit all positions if they reach a portfolio-wide drawdown of 5% in a day. They cap margin to equity at 25%, though it typically runs around 7 to 10%.

Zoi earned solid returns: 36.12% in 2010, 25.34% in 2011 and 32.66% in 2012, trading basically for friends and family and looked to raise more assets.

In 2013 Zoi got its first institutional client when Jack Schwager provided an allocation from the ADM Investor Services Diversified Strategies Fund he was co-portfolio manager of, which is ironic as Terpilowski first got interested in technical trading after reading a Jack Schwager book.

The Telio program has produced a compound annual return of 20.36% since April 2010 with a Sharpe ratio of 1.05. It is up 6.56% in 2014 through October.

Zoi is looking to expand its program to 40 markets, which should be no problem as the strategy has already been rigorously tested. As Tsahas says, “If we can’t see it in a model, validate it and make sure it is not curve fitted, we are not going to trade it.”

StockChartsFX is Now Open Source

Rob's Blog

I have received several inquiries asking to provide examples on how I created the JavaFX candlestick chart that I have used in the trading apps that I am currently working on, pictured below. enter image description here I’ve done a bit of work to separate the chart out from the rest of the application and create a chart new library which I’ve open sourced at checked in to GitHub at: The project includes both the JavaFX code as well as the style sheet used to style the component. There isn’t currently a lot of functionality built in to library, and the code is a bit messy, but contributions are welcome. twitter: @RobTerpilowski

Written with StackEdit.

View original post

Make Money Online Automatically. Trading Commodities with JavaFX and the NetBeans Rich Client Platform

Rob's Blog

Ok, so maybe it isn’t quite as easy as it sounds, but we were able to leverage an automated trading application we had previously written and the modularity of the NetBeans Rich Client Platform to create a commodity trading application that will interface with, and allow us to place trades with a new commodity broker.

Even though the original application was for the purposes of automated trading, we were able to use many of the same NetBeans plugins we had developed in order to create the new application, as well as utilize JavaFX to put a nice polished UI on the app.

The login screen is below. The commodity images on the right side of the screen scroll down the UI and represent each commodity market that we trade.
enter image description here

After logging in to the application, those same commodities are in a dock at the top of the window. The images…

View original post 205 more words

Monitoring Real-Time Commodity Prices using JavaFX, NetBeans RCP, and Camel

Rob's Blog

Zoi Capital is a commodity investment firm which trades in the commodity futures markets on behalf of clients, with offices in New York and Seattle. We needed an application which could display the commodities we were currently holding as well as show any open profit/loss of our trades in real-time. In addition, we wanted to display the current performance of our trading strategy (named Telio) along with a comparison of the current performance of the S&P 500 stock index as well as the Dow Jones UBS commodity index.

Trades are placed from the Seattle office, but are monitored throughout the day from the New York office, so the application (which would be running in New York) needed a way to stay up to date with the current trades. The application also needed to be aesthetically pleasing as it was planned to put it on a large 50 inch LCD in…

View original post 556 more words

Effects of a Portfolio Wide Stop Loss on Trading Strategy Performance


The daily returns of our trading strategy can be volatile, especially during periods of extreme overall market volatility across asset classes. During these times, multiple signals are usually triggered within the same asset class which has the effect of amplifying the daily gains/losses of the trading system. The greatest daily gain/loss amounts have been more than 9% historically. A day when 9% of account equity could be lost is difficult to stomach for any investor, institutional investors especially.

Every position that the strategy trades is equipped with its own stop loss order, however we would like to investigate the idea of a portfolio wide stop loss. With a portfolio wide stop loss, we would like to exit all positions if the account equity drops by x% in a single day, This could help mitigate the risk of seeing another day with losses greater than 9%.

Test Process

For this test we used intraday data from IQFeed and the dates of our actual historical trades. A custom component was written for Multi Charts to read the strategy’s trade history and map the execution dates to the intraday data. A new strategy for MultiCharts was then written to close all positions once the account equity dropped below a specified amount on any given day.

All 19 futures markets that the strategy trades were loaded into MultiCharts and the historical data was separated into an in-sample and out-of-sample group. The in-sample data range was 7/2007 – 7/2010, and the out-of-sample data range was 8/2010-4/2014.

A baseline test scenario was run on the in sample data with no portfolio stop loss with additional tests run with stop loss values ranging from 2%-7%. The best performing stop loss would be selected, and tests would be run on the out-of-sample data for each stop loss level to see how they performed moving forward.

The test cases would assume a starting account equity of $1MM, and slippage would vary based on commodity, ranging anywhere from $0 – $100 per contract depending on historical slippage that has been observed in each of the markets that are traded.

The goal of the stop loss is to minimize the negative impact to the trading strategy performance that the stop loss may have, while minimizing the risk of a large loss in account equity during times of extreme volatility.

In Sample Results

As previously mentioned, a base scenario was run with no portfolio stop loss, and then tests were run with stop loss values ranging from 2%-7% in 1% increments. The table below shows the results for the in-sample tests with the test metrics explained below the table.










Net Gain








Total Return








Profit Factor








Max Draw %








Return/Max Draw








GTP Ratio








Worst Day








Best Day








Stop Loss Days








Table 1: In-Sample Test Results


Net Gain: The profit earned by the trading strategy during the in-sample period.

Total Return:: The strategy’s % return during the test period.

Profit Factor: Gross Profit divided by Gross Loss

Max Draw %: The maximum drawdown experienced by the strategy.

Return/Max Draw: The total return divided by the maximum drawdown. This is a good measure of risk adjusted return.

GTP Ratio: Gain-To-Pain ratio. This performance metric was developed by Jack Schwager and is also a good measurement of risk adjusted return. The GTP ratio is calculated by dividing the sum of the monthly returns by the sum of the returns for months that had a negative return. This the effect of penalizing strategy volatility to the downside, but not upside volatility.

Worst Day: Strategy return on the worst day over the test period.

Best Day: Strategy return on the best day during the test period.

Stop Loss Days: The number of times the portfolio stop loss was be triggered.



Some metrics were charted across all stop loss values to help decide where an appropriate stop loss value may be.











Based on the results, the strategy’s performance begins to suffer with anything greater than a 5% stop loss amount. Results for stop loss values of 5% or greater are static as there were not any days with more than a 5% loss. The value for worst day is greater than the stop amount in some cases, as in the

-4.71% maximum loss with a 4% stop due to positions due to slippage. A 5% stop loss will be selected as it will help protect the account equity from the -9% day with the least impact to the trading results based on the in sample testing.

Out of Sample Tests


Out of Sample tests were run from 8/2010 – 4/2014 to see how the various stop levels performed moving forward. The results of those tests are below.










Net Gain








Total Return








Profit Factor








Draw %








Return/Max Draw








GTP Ratio








Worst Day








Best Day








Loss Days








Table 2: Out of Sample Results












Based on these result, the 5% stop loss continues to perform well in all areas, except for strategy drawdown where it is the worst of all stop loss values. This however is made up for by the fact that the total system return is the greatest out of all the stop loss values, which means that the ratio of the total return to max drawdown is comparable with values greater than 5%.


Moving forward, a daily portfolio stop loss will be implemented at the 5% level. If account equity drops by 5% since the previous day, then all positions will be exited. Further studies could be done to see if improvements can be made to this strategy, such as only closing unprofitable positions, or closing some, but not all positions in specific sectors, depending on how the overall sector is performing.


twitter: @LimitUpTrading
twitter: @RobTerp

Limiting Trading Strategy Drawdowns with an Equity Curve Filter

In an effort to limit the drawdown of a trading system I like to employ a filter on the strategy’s equity curve.  Meaning that if the strategy runs into a rough period I have a set of objective rules that tells me when I should take the strategy offline. 

The most common type of filter I employ for the equity curve is based off of a 100 trade moving average of the curve.  When the equity curve is trending above the average the system remains active, when the equity curve drops below its average the system is taken offline until the curve turns upward again. 

I typically trade mean-reversion type strategies which have a  typical trade distribution with many small winning trades with the occasion large loss. The trades are also short in duration with anywhere from 3-12 trades per day placed by each strategy.  Its after a string of large losses occurs that the curve will drop below its moving average.  This type of filter would not work with a typical trend following strategy which would have many small losses and the occasional large win as the filter would likely take the strategy offline before it has a chance to place one of its few winning trades.

Below is the equity curve of the AUD/NZD strategy which I have been trading for much of the year along with its 100 trade moving average.  Recently the strategy has experienced a drawdown which erased nearly all the gains that had been earned through the year. The goal is to attempt to reduce the severity of the drawdowns. 





If the strategy is turned off when the equity curve drops below its 100 trade moving average we end up with the following result. As can be seen, when the strategy is in an uptrend the filtered equity curve provides a slight drag on profitability.  But once the equity curve takes a noticeable downward turn





Just so we’re comparing apples to apples, the stats for the unfiltered strategy will start at trade 100 (which is where the 100 trade MA starts).  The moving average filter cuts nearly half the trades out over the time period, reducing the drawdown by nearly 50%, as well as increasing the system profit by 37%. 

  Original Filtered
Trades 432 226
Avg. Trade (Ticks) +0.31 +0.83
Total Profit (Ticks) +135.7 +186.8
Max Drawdown (Ticks) -443.6 -226.90


In theory one could apply any number of technical indicators to a strategies equity curve in an effort to help improve its profitability, as well as to make a determination if a strategy has stopped working and should no longer be traded.  I also blogged in the past about tracking the overall equity curve of a trading account which is trading a portfolio of strategies and move excess funds into and out of the account.

I am continuing research on this topic and will be exploring other possible means for determining when a strategy should be disabled or should be removed from a portfolio all together.


twitter: @LimitUpTrading
twitter: @RobTerp

Weekly Update 9/30/12: Live Trading AUD/NZD with the Arb Trader Application & Update on New Features

I’m a few weeks behind on updating the results of the strategy as I prepared a presentation for the JavaOne conference which took place this past week.  In the meantime, the AUD/NZD version of the strategy has taken a serious beating, erasing almost all the gains since the system started trading in March. The strategy was also stopped out during the week when it hit its 100 pip stop loss.  When this event happens all other strategies will cease trading as well (EUR/DKK), until manually started again.  This is to ensure that some crazy event doesn’t take all the other strategies down with it.

This week’s number are below. All results include commission.

Week of 9/30/12

# of Trades 18 14
Winning Trades 61.1% 85.7%
Avg. Trade (Ticks) -10.33 +1.18
Total Profit/Loss (Ticks) -185.9 +16.5

Total since inception

# of Trades 485 156
Winning Trades 77.3% 87.8%
Avg. Trade (Ticks) +0.04 +0.79
Total Profit/Loss (Ticks) +20.3 +123.7

* 3/11/12
** 7/22/12

Due to the large drawdown that the AUD/NZD strategy is experiencing, I have implemented an equity curve filter on the strategy so that it remains out of the market until performance improves.  An equity curve filter takes the average cumulative gain/loss over the last 100 trades, and compares it to the current gain/loss amount of the strategy.  If the current amount is less than the average, then the system stays out of the market.  Below is a chart showing the current equity curve in blue, and the 100 trade average in red.  The y-axis units are number of ticks the strategy has made/lost.  As you can see the current equity curve in blue has fallen well below its 100 trade average.




Update on Progress of the Arb Trader Application

Currency Strategy

Upcoming bug fixes and new features

  • ArbTrader now has the ability to add multiple accounts and data providers, whereas previously, everything was hardcoded.
  • A JavaFX chart component now has been added to the application, which I will be adding the graph (above) to the AUD/NZD strategy tab.

End-of-Day ETF arb strategy

No updates are planned for this strategy this week.

Intraday ETF arb strategy

  • Continue monitoring 4 pairs in the paper trade account.

Twitter: @LimitUpTrading
Twitter: @RobTerp