UPDATE:
It looks like the service I'm using as my public server broke all their links today. The new link are of this form:
http://dl.dropbox.com/u/39904/Blog%20Datasets/Sys3/sys3.m
instead of:
http://dl-client.getdropbox.com/u/39904/Blog%20Datasets/Sys3/sys3.m
The pattern to get the new links from the old ones is to just delete "-client" and "get". Hopefully they will restore the old links since I had posted files on many pages.

Here's a video guide to using the Interactive Brokers API with Matlab.

The following are the notes that go along with the video, it follows each step
install trader workstation (i.e. tws)
http://individuals.interactivebrokers.com/en/software/installationInstructions.php?ib_entity=llc

install the api
http://www.interactivebrokers.com/en/p.php?f=api&ib_entity=llc -> Proprietary API tab -> choose appropriate download
online api guide fyi
http://www.interactivebrokers.com/php/apiUsersGuide/apiguide.htm

enable the activex api
run tws
configure > API > enable ActiveX and Socket Clients

register the activex server
windows start button > run > regsvr32 "C:\Program Files\Jts\ActiveX\Tws.ocx"
restart the computer
run tws

run matlab
set up preliminary variables with the following commands
>> global eventdata orderid; eventdata = {}; orderid = 1; f = figure; set(f,'Visible','off');
connect Matlab to the api
copy twsevent.m to your current Matlab directory
>> tws = actxcontrol('TWS.TwsCtrl.1',[0 0 0 0],f,'twsevent');
>> tws.connect('', 7496, 1);
test it!
use the newcontract.m script- copy it to the current directory
>> newcontract
>> tws.reqMktDataEx(orderid, contract, '', 1)
>> tws.reqCurrentTime()


S = INVOKE(OBJ) returns structure array S containing a list of
all methods supported by the object or interface OBJ along
with the prototypes for these methods.
invoke(ib)
METHODSVIEW(OBJECT) displays the methods of OBJECT's class along
with the properties of each method.
methodsview(ib)
Webinar:
http://www.interactivebrokers.com/en/general/education/priorWebinars.php?ib_entity=llc

Here are the two extra files needed
newcontract.m
twsevent.m
UPDATED: Here's a script of the above instructions in case you get an error: testtws.m

Follow along in notes above and it should be clear enough.



Like I mentioned, please suggest how the process might be improved if you have ideas. Anything else is welcome too.

51 comments:

Eric D said...

Max - Thanks for the info, I definitely want to try it out. I would be very interested in connecting Matlab to another broker via FIX using QuickFIX to make a Matlab solution broker neutral. Any ideas on how to do this?

I think it makes sense to use FIX to reduce the time required to rebuild a system when you change brokers.

Regards,
Eric

Max Dama said...

Eric,

Thanks for your comment.

It motivated me to do some research on FIX. Creating a broker-neutral Matlab system development environment with QuickFIX could be a valuable product. You could use the QuickFIX C++ API in Matlab using a mex-file. I can't seem to find information on inexpensive brokerage services with FIX support. Do you know of retail brokers with FIX connectivity?

Regards,
Max

Eric D said...

Max - I think Open E Cry has FIX connectivity but am not positive. I know they usually promote the use of their API but they note FIX connectivity on their site. http://www.openecry.com/services/institutional_clients.cfm

One of my accounts (I have multiple for redundancy & backup purposes) is with them & they are a good broker to use.

It looks like Genesis Securities does as well. http://www.gndt.com/automated/fix.htm

Pretty much any large brokerage that is interested in high volume automated trading would likely support FIX.

Regards,
Eric

Chase said...

Hi Max,

This is really helpful. I'm getting an error I was hoping you could help with. When I attempt to connect to the TWS, I get the following error message:

??? Error using ==> comeventcallback at 25
Error firing event 'nextValidId' to 'twsevent'.

Warning: Error occurred while evaluating listener
callback.

...and a couple more like it. Let me know if you have seen anything like this.

-Chase

Chase said...

Hi Max,

This is really helpful. I'm getting an error I was hoping you could help with. When I attempt to connect to the TWS, I get the following error message:

??? Error using ==> comeventcallback at 25
Error firing event 'nextValidId' to 'twsevent'.

Warning: Error occurred while evaluating listener
callback.

...and a couple more like it. Let me know if you have seen anything like this.

-Chase

Max Dama said...

Chase,

I encountered that error too but it resolved itself after some tweaking. I can't remember what fixed it exactly but I think it had to do with changing the name of one of the functions. Here's the script I use to start the whole thing up in one command: testtws.m. To use that, start up TWS (make sure the configure>api>enable ActiveX option is checked) and then run the script. Also make sure twsevent.m and newcontract.m are in the current directory.

If that doesn't work then I don't know how to fix it. There is some scattered information on the IB discussion boards, search for "Matlab".

Regards,
Max

Chase said...

Hi Max,

Thanks for the m-file. It works perfectly.

Chase

Max Dama said...

Chase,

Great. I'd like to see what kind of framework you end up creating so please keep in touch. I'll be posting the code for my system in the next few days but it's not heavy in the API, which I only recently learned. Basically it uses the API for historical data and for submitting orders, after I verify the orders by hand.

Regards,
Max

Achilles said...

I am using Matlab R2007b (7.5) and I get the following error:
?? Error using ==> feval
Input PROGID does not represent an Activex control.
If this PROGID used to work before, please check vendor's
documentation for equivalent activex control progid.

Error in ==> testtws at 6
tws = actxcontrol('TWS.TwsCtrl.1',[0 0 0 0],f,'twsevent');

Any ideas on what might the problem be ?

Max Dama said...

Sorry Achilles, I have no idea what that error might mean.

Regards,
Max

Anonymous said...

Max,

I tested your Matlab/TWS test software. It worked with XP. But I am a Mac guy and it does not have ActiveX controls. Is there any simple way to do the same for mac osx?

Thanks.

Martin

Max Dama said...

Martin,

You could try using a Java wrapper from within Matlab to access IB's Java API. I haven't tested it at all.

Regards,
Max

martin said...

Max,

I get actxcontrol error:

??? Undefined function or method 'actxcontrol' for input arguments of type 'char'.

Error in ==> ConnectToTWS at 7
tws = actxcontrol('TWS.TwsCtrl.1',[0 0 0 0],f,'twsevent');

Any ideas?

Max Dama said...

Martin,

I'm not sure. ActiveX is apparently only for Windows so that could be the problem. One good place to get help is this site's forum: http://www.tradingwithmatlab.com/

It's just getting started but I know one person there who can probably help.

Regards,
Max

Martin said...

Max, in your twsevent.m file this does not make sense to me:

eventdata(length(eventdata)+1,1) = {d};

Is that an error?
Please, can you explain it?
Thanks.
Martin

Max Dama said...

Martin,

Matlab automatically expands the cell array eventdata and puts the info in d in the new cell.

Regards,
Max

ben said...

Hi,

Thanks to your examples i'm able to generate a simple order... but i was wondering if you had an example of a combo order (ex: strangle with a limit price)

Thanks for your help.

Ben said...

Hi Max,

I did found some documentation that did alow me to crease single securities orders.

But i will love to be able to creade combo orders (ex: strangle with a limit price)

I will really appreciate if you had any code sample or documentation that could help me

Thanks in advance

Ben

Max Dama said...

Ben,

I haven't done this so I don't have example code. On page 203 (PDF page 203, printed document page 199) of the API documentation there is a section on combo orders. Here's a link to it.

If you get it working with example code, I'd like to make it available to anyone if that's ok with you.


Regards,
Max

Ulf said...

good tutorial. i will try it the next days.

Mechanistician said...

Good stuff, worked perfectly...

Thanks!

Max Dama said...

You're welcome.

I like your site too.

Max

LifeOnEight said...

I'm getting the same "PROGID does not represent an Activex control" when I try to create an instance (i.e. tws = ...) that Achilles mentioned above on May 28, 2009.

I have previously been able to get this API to work on another machine, however. The only two pertinent things that have changed now on this new machine: (a) I am using Vista, and (b) I have MATLAB 2009a running (before it was 2007a)

I have checked with regedit and the OCX was correctly registered. It exists as TWS.TwsCtrl.1 which is what we are trying to use as PROGID. So it exists, but MATLAB's actxcontrol() claims otherwise...

Max Dama said...

I don't know what the problem is, LoE.

Max

asudjian said...

Max,LoE
I think the problem occurs for Windows 64 bit system. I have my code run fine for 32 bit Windows but encounter the same problem when I run it in 64 bit Windows. The problem still persist after installing C++ and Java distribution package as explained in IB website. Anybody can help?

LifeOnEight said...

asudjian: You might be on to something: I am indeed now running Vista 64-bit. Thanks for the hint. Hopefully we can figure this out together... I'll report back if I find a solution; please do so as well.

yoyoteng said...

thanks Max. the code works wonders! I've spent the past few days browsing through MetaTrader's mql4 documents, and was going to jump into building one Expert Adviser, but now seeing your post and a post by mechanistician@blogspot, I've decided to give TWS's ActiveX API a try first!

Max Dama said...

Glad it helped yoyoteng.

mr_tomcat said...

Hi Max,
For a novice programmer how difficult would it be to connect Matlab to TWS via JAVA instead of ActiveX? I'm not trying anything fancy. Mostly just need account positions and maybe some tick data. Do you reckon everything changes once actxcontrol departs the game?

-mac user

Max Dama said...

Mr_tomcat,

It's possible, but not trivial. I could put up a note on it sometime soon if you'd like.

Regards,
Max

mr_tomcat said...

I feared this was the case. Any insight regarding Matlab to IB via Java would be much appreciated if you get a chance.

Best,
Tom

Max Dama said...

mr_tomcat,

I now have some people working on the Matlab-Java-IB connection. I'll let you know how it progresses.

Regards,
Max

mr_tomcat said...

fantastic. Thank you, captain

-T

Anonymous said...

for all who receive the progid error
... the progid error occurs in matlab x64 version due to the fact that matlab is not able to load a 32bit control ...

Anonymous said...

Hi
I am getting the "Input PROGID does not represent an Activex control." problem. I am trying to do this on a 64bit machine. The previous email seems to infer that there is a problem with 64bit. Has anyone got a solution please?

Aris said...

Max - Great info. I try to follow your method. But didn't work.

I use ubuntu 9.10, matlab 2009b, tws and API as unix version.

TWS and API works fine. But i didn't register ActiveX server, coz i didn't use windows.

When come to matlab event handler, it got problem of running "tws = actxcontrol('TWS.TwsCtrl.1',[0 0 0 0],f,'twsevent');"

The error message is:
Undefined function or method 'actxcontrol' for input arguments of type 'char'.

I figured this is because ActiveX server was not running.

Do u have a solution for this problem?

Aris said...

Max,

Apparently, connecting IB API through ActiveX only works on windows. In order to run IB API on linux, we need to connect matlab and IB through Java. It says supported on IB API, and matlab has java connectivity also. It seems it's possible to follow the spirit of your method, implement it on Java, then it will work on any platforms.

API says support java:
http://www.interactivebrokers.com/php/apiUsersGuide/apiguide.htm
------------
The ActiveX control to link through a Visual Basic and .NET application (on Windows platforms only).

The Java API to link from a Java application (for all platforms).

Michael said...

Hi Max,

i would be interested too in a java version. I use it on a Mac OS X10.5 with matlab 2008b, tws and API as unix version.

Thanks,
Michael

Max Dama said...

Aris and Michael,

I've seen a platform-independent Matlab connection through Java that one of my friends worked out. He shared with me how it worked but it wasn't pretty. He won't let me share what he did for free unfortunately. He's actually made a pretty good system after following this tutorial and spending a lot of time. I've been impressed and asked if I could share some of it before but he said no. He'd probably sell it since it's not really a competitive advantage, just a big chunk of time that you have to spend.

Regards,
Max

Michael said...

Hi Max,

thanks for trying. I already have a working tradingsystem and has been running for a while. I would like to do the finale step to an automated system. If I would be able to use the java api, i could call it a night.

It looks more likely that I will get Windows 7 and just screw Mac OS X.

Regards,
Michael

PS: Would your friend share, how to connect to TWS through java api?
Just a simple m file would be nice :)

Max Dama said...

Michael,

As far as I remember you need to write a java jar file too, it's not just in Matlab.

Max

Liangyi2012 said...

Hi max,

is it preferable to use matlab solely on automated trading? I mean matlab isn't very good at GUI right? Another thing matlab isn't very good at is connecting with ib. Although in this article, u have solved the connectivity problem partially, based on windows platform.

for platform-independent trading, an easy choice is using Java to build up the GUI and connect to ib. GUI capability is a built-in capability of Java. Connecting to ib has examples from ib Java API docu also.

Could u give some comments on the design that using Java to build GUI and data adapter to ib, using matlab as a numerical engine, that dont' talk to ib directly, but talk to Java data adapter only?

aris

Max Dama said...

aris,

I don't think a GUI is too crucial for automated trading.

I've worked out the IB Java API to Matlab connection but it's pretty complicated so I've been putting off the write-up. I'll try to do it sometime soon.

Regards,
Max

Liangyi2012 said...

Hi Max,

Something interesting to share with you. I tested your method to link matlab with tws on windows. It works perfect. In particular, "tws.reqMktDataEx(orderid, contract, '', 1)" works fine.

But on linux, i tried to use java API to connect with IB with IB's exmaple code. It also use this version "reqMktData(p1,p2,p3,p4)", but it won't return any data.

aris

Max Dama said...

Aris,

I haven't used the Java demo code or API so I don't know how to help.

Regards,
Max

Tony said...

Could you please repost the attached files as the links are dead?
Thanks a lot

Anonymous said...

What about R, R also has a IB package
called IBrokers. http://crantastic.org/packages/IBrokers

Have you ever try R and IBrokers ? Any comment?

Max Dama said...

Anon,

That's a good one too, but the community isn't as big as the Python IbPy community and at the time I checked it out, it wasn't finished.

Regards,
Max

Anonymous said...

hi there,

i tried to set up ib with matlab, but the necessary .m files can not be found

newcontract.m
twsevent.m
testtws.m

can anyone help me? thanx

regards,
serge

Max Dama said...

Serge,

Please see the update I just posted at the top of the note.

Regards,
Max

Anonymous said...

Thank you!

Best regards,
serge