As I mentioned before, I now find MATLAB to be a good platform not just for backtesting, but for automated execution as well. Of course, not all brokerages have API's that connect to MATLAB. My example codes are for submitting orders automatically to an Interactive Brokers account.

In general, I find that writing execution programs in MATLAB is a breeze compared to C++, Java or even C#. It takes about 1/5 the development time of a C++ program. Any performance limitations will probably not be due to MATLAB, but to the latency of your brokerage in updating positions and order status.

83 comments:

Quick question: have you tried Mathematica? (It has a powerful and quite elegant set of functions based on a "list" methodology that might map well to trading strategies. Or, random things like synthetic aperture photography...)

Thanks again for another terrific article. Your book just keeps giving via the "embedded" password for your premium site !

I know your Bollinger code is designed more to show us how to implement MATLAB2IB than as a trading system, but since you are obviously really good at Matlab, how would you add a trailing stop exit condition.

I understand the logic - what is the highest open profit, what is current open profit, if different by X percent then exit, but I am having trouble with the Matlab syntax.

Any chance you could provide a simple example in Matlab code for either the Bollinger example or as a standalone?

Hi G-Fav,I have programmed in Mathematica before. However, I feel that MATLAB's array processing capability is more suited to statistical arbitrage research. Furthermore, I am not sure there is a Mathematica API for connection to brokerages.Ernie

Hi Anonymous,I will look into providing sample code for trailing stop at some point in the future. But you can always keep track of the maximum price of your stock since your entry in a Matlab variable. So any time the Last price generates a return (drawdown) that is below a certain minimum, send a market order to exit your position.Ernie

Loved the book Ernie, several of your helper functions lie on my MATLAB path.

If anyone is left out in the cold with IB, the MB Trading SDK also integrates well with MATLAB. It hasprefab ActiveX controls that are a snap to implement in the GUIDE for creating custom trading interfaces.

I'd like to trade FX but with IB you don't get a last price in the FX data feed, you get the last close from the previous session, but not the last trade price in your current session.

What's a good way to approach this this problem? As a price taker in FX you often have to take the spread so averaging (take the midpoint) of the bid/ask isn't such a viable solution. Any recommendations?

A question and a comment,What is the advantage to use the IB2MATLAB software over the free version using ACTIVEX. Here is a sample code how to connect directly via COM.(http://www.matlabtrader.com/code.php?project=InteractiveBrokers&file=IBexamples)

I believe using a matlab timer object will make the code more friendly.

Matt,If IB does not provide last price for currencies, you may have to subscribe to Bloomberg and use Matlab's Datafeed toolbox to get Bloomberg data. This is of course a much more expensive proposition, but well worth it if you can generate revenue from your model.Ernie

Anonymous,There may not be an advantage in using matlab2ibapi over using the free version from matlabtrader. However, the cost of matlab2ibapi is so low, and the customer service so friendly, that I don't consider "free" an intrinsic advantage. The greatest cost in trading is the loss from bad execution or bad models.Ernie

ExchangeAPI refused my request for a fully functional trial. I cannot test this API for reliability, accuracy, and latency against my current systems so I will have to find a solution using the free MatLabTrader version.

I just can't sink $300 into another software that sounds good unless there is a distinct advantage over my current infrastructure.

I have been using the matlabtrader.com version for a long time now and it works perfectly. Of course you have to give it some tweaks here and there, but it provides you with full functionality. There are quite a few examples included, so it's really easy to get started. I would highly recommend it to anyone who wants to trade using the API, but doesnt want to spend money ;)

Dr. Chang,this is somewhat unrelated to this post, but related to your book. Since you mention Jim Simon. I thought you would appreciate this:http://www.economist.com/finance/displaystory.cfm?story_id=13751628

as well as this particular comment attached to the story above:"Henry Leeds wrote:May 29, 2009 2:49Jim Simons is a Pool Operator with the ability to raise large amounts of money from investors. He lacks the mathematical skills and knowledge to develop a really superior Trading System. His claim to fame rests on his years assisting Shiing Shen Chern, a brilliant mathematician who generously allowed Simons to add his name to the 1974 paper Chern wrote. The Medallion Fund was created by Elwyn Berlekamp, a brilliant Professor of Electrical Engineering and Mathematics at Berkeley. Berlekamp utilized his knowledge of Claude Shannon's revolutionary Information Theory to create this marvel. Shannon was Berlekamp's PhD Advisor at MIT. Berlekamp developed his Medallion Fund in a matter of months and its incredible performance is described on Berlekamp's website. Simons wanted Berlekamp to re-locate to Long Island and to continue developing the algorithms comprising his Medallion masterpiece. Berlekamp did not want to leave Berkeley and as a result he made a huge mistake. He sold the rights to his invention to Simons for six times what it had cost him - a relatively small amount. He now states on his website that the Medallion Fund is worth many thousands of times the dollar amount that he received for his achievement. The Renaissance RIEF hedgefund is an example of Simon's creative abilities. Its performance is pitiful and has resulted in investor withdrawals of 18 billion dollars. Renaissance investors have complained bitterly how their investment has faired so poorly while the Medallion Fund, reserved exclusively for Renaissance employees, has done so well. One can certainly understand their vexation."

I've been in the trading industry for a little while and everybody and his mother things of Jim Simon as being a god. Mr. Leeds seem to offer another reading of Pr. Simon's succes which came as a shock to me.

Charles,I actually have not used TradeStation myself. However, I have heard that the historical data that TradeStation provides is not of the highest quality. Furthermore, the kind of strategies you can construct with their proprietary language are more limited than the ones you can construct with Matlab.Ernie

Dear Anonymous,Thank you for highlighting the comments on the James Simons article. Actually, it has been well-known that Renaissance Technologies has not been very expert in equities strategies. But this is not unusual, few funds are excellent in both futures and equities trading. Apparently they require quite different mindset and perhaps skillset.Ernie

Hi Ernie, Your book is extremely good. No hype. Just a systematic process. It has helped me quite a bit. I was going through your cointegration posts. Is there a sample MATLAB program where this has been implemented ?

I'm not so sure about MatLab2IB's "customer service so friendly" after N N's comments I emailed them asking if they can confirm that the program will definately work with IB's FX, particularly routing with IDEALPRO - I never got a reply.

So I am now playing around with http://www.matlabtrader.com, I am going to try and code your example with matlabtrader.com, if I get it working well maybe you might like to post the comparision code.

I am one of the authors of the MATLAB2IB API. We really apologize. We are not sure how we missed your email. Can you be kind enough to email us again. We are being inundated with Trial Requests and other emails and so we might have missed it. You can email me directly. YES, MATLAB2IB will work with IB FX. As long as you have permissions with IB, MATLAb2IB will have no problem putting your order through. Infact, SOme of our license owners do use it speciifcally for FX.

Regarding NN: He asked us if we can provide him a Trial Version with Full api functionality. As a Policy we decided not to provide it. It is as simple as that. There are many reasons which I can discuss separately.

In such a case, you can always open TWO or more matlab sessions on the same computer using the same license. So you can use 1 session for algo trading and another one for your use.Alternatively, you can use compiled versions.

Has anyone here looked at some open source alternatives including the R stat package? I believe interactive brokers enables you to write a trading model in R, and then interface with their back end for your execution system.

If you really need computing speed, LUSH is an alternative, as it has easy integration with C/C++ code, ample numerical, statistical, and machine learning libraries, and a simplified version of lisp.

T,I haven't come across any books using Excel for backtesting. But since Excel is such a easy tool to use, you can probably figure out yourself how to code it based on some of the examples in my book.(Caveat: it is not easy to run regression fits in Excel on multiple stocks simultaneously.)Ernie

HI perhaps I'm late to the party, but I just stumbled upon this topic. I noticed someone complaining about the price of MATLAB2IB, it's $600/year. If you wanted to repeat what the author of MATLAB2IB (now called QUANT2IB) you can take the IB examples written in C++ and use the information in this link http://www.mathworks.com/support/tech-notes/1600/1622.html to compile them as a Matlab subroutine. If you wanted to use another Retail firm than IB, and that firm has C++ APIs then this method will work there as well. If you don't want to get your hands dirty doing this then you probably can hire a contractor to do it for under $600.

cbucks,Yes, you can run a continuous loop to monitor the price, or you can use an event-driven API such as the one described by maxdama.com: http://www.maxdama.com/?p=127(or simply search for "Matlab API" on his website. This way, any time a price changes, a callback function that you provide will be called.Ernie

Hi Anon,The matlab2ib program works by retrieving the last price every time you request one, and is not event-driven. So you can request it once every 250ms, which is the maximum update rate of IB.Ernie

So, if someone wanted to create a pairs trading program with this sample, they would create a "localsymbol2", then request the market data for that particular security and have the program execute buy or sell orders opposite to the primary security with accessory if loops?

And for calculating the deviation and lookback periods, one would be able to adjust it by modifying the zscore/'lookback'/'entryz'/'exitz' to represent say linear regression instead of bollinger bands?

So, if someone wanted to create a pairs trading program with this sample, they would create a "localsymbol2", then request the market data for that particular security and have the program execute buy or sell orders opposite to the primary security with accessory if loops?

And for calculating the deviation and lookback periods, one would be able to adjust it by modifying the zscore/'lookback'/'entryz'/'exitz' to represent say linear regression instead of bollinger bands?

So, in the buy order for security 'localsymbol' part of a loop, right below it, one would place a sell order for security 'localsymbol2' and make it all part of a single loop to make it a tandem trade?

And Linear Regression or EMA or any other indicator should work as well provided the proper zscore parameters are given?

Hi Anon,Yes, I learned recently that you can send orders from Matlab's Trading Toolbox.

You can certainly add various indicators to the sample program. But I doubt that it would make much difference in profitability. The main improvement will be in execution strategy, such as using limit orders.

I am new to quantitative trading. I am thinking to get a student version for Matlab. I wonder if it is sufficient to do backtest on stock, ETF and FX? I am currently reading your book and was inspired to be a quant. Currently, I am a Teacher in Singapore.

I am looking for a stop loss and take profit strategy on MATLAB. I work with MA strategies so I need to have a command that compute take profit and stop loss strategy. Could you help me have it? Do you have the codes on MATLAB?

Hi Sarkhan,I assume you are trading a mean-reversal strategy?If you use Bollinger bands, both profit cap and stoploss are automatically built-in.Please see my book Algorithmic Trading, Example 3.2 and the codes therein.Ernie

I am wondering: do you actually need to have subscription to market data through IB (hence pay the subscription and exchange fee) to get the data, or can you get delayed data and FX data in any way with this API?