File Exchange

image thumbnail

IB4m - Interactive Brokers API in MATLAB

version (729 KB) by Abel Brown
Access historical data, real-time market data, place orders, options chains, and more


Updated 03 Mar 2021

From GitHub

View Version History

View license on GitHub

Interactive Brokers API in Matlab. Get access to the entire TWS API from within MATLAB. Access historical data, real-time market data, options chains, contract details, place orders, portfolio notifications, and more! Includes complete set of tutorials for each API call. Visit GitHub page for Quick Start Guide:
Certainly feel free to ask questions here on the FileExchange but much faster to open issue over on GitHub which goes straight to my email:

Cite As

Abel Brown (2021). IB4m - Interactive Brokers API in MATLAB (, GitHub. Retrieved .

Comments and Ratings (44)


Abel Brown

@MRossi, yes fundamental data is supported. Feel free to open issue over on GitHub if have any trouble.


I wanted to know if it was possible to access fundamental data from matlab with the API ?

Abel Brown

@Felipe yes, it works on a Mac. Feel free to review issues at -- there is lots of help there from other user discussions. Also, if needed, you can open a new issue and I can help get you squared away.

Felipe Lopez

Hello, does it work in mac?

I'm getting this error:

Undefined variable "com" or class "com.tws.Handler".

Robel Keleta

Abel Brown

@Swen Thanks! I will follow up on the Github issue you opened here

In the mean time, be sure to checkout the IB API for adv order algorithms here:

swen swin

First, thanks for a great API wrapper!

Then the question, I would like to place an MKT order with stoploss and takeprofit. like 20 ticks each way or so.

I can do it for a LMT order, but then I have to give the exact prices for buy-limit, tp and sl, and cant use the the relative way as above. (I accomplish that by placing 3 orders with the two sl (STP) and tp (LMT) orders connected to the parent).

If I could place the initial order as a MKT, and then get the fill-price, then I can calculate the other two order prices, but I cant find that value anywhere.

My guess would be the ExecutionDetails, but when I look at the ExecutionDetailsExample, there seems to miss the information about how buf gets populated, and I have not been able to find that information somewhere else.

Could you please help me? Am I right with the missing part in the example, and is there a better way to accomplish what I want?

I use the 973.jar version,

thanks a lot,

Alan Sun

Jonathan Alden

Abel Brown

@Philipp, thanks for asking. In your InteractiveBrokers account, you need to activate market data. Once you have market data activated in your account then you can make a request from API when markets are open. Be sure to read the latest IB API docs for level 1 and level 2 mktdata ( as there is a lot to know about retrieving market depth. Most of the time, a historical data call or real-time bars (reqRealTimeBars) is better solution unless you really do need streaming top of book action (when markets are open). To address the matching signature, IB API now requires to specify extra boolean for `regulatorySnapshot` in addition to the `snapshot` boolean. That is, just pass two `false` when requesting mktdata like this: reqMktData(reqId,contract,genericTickList,false,false,[]). I will include the change with a few other routine updates in IB4m later this week. Do not hesitate to open issue on GitHub if you need anything additional.

Philipp Lechner

Hi Abel,
thank you for your work! I'm using Matlab 2018a. I got the AccountSummary example running but the MarketData example gives me this error:

"No method 'reqMktData' with matching signature found for
class 'com.ib.client.EClientSocket'"

Could you please help me? What am I doing wrong?

Thank you very much


Abel Brown

Updates now live for new Interactive Brokers API version 9.73 which includes BracketOrders, OrderConditions, CommissionReports and more. The older 9.72 API has been tagged in git as "v9.72" and is still available, if needed. Don't hesitate to open issue on GitHub if need any help/support.

Abel Brown

@MRossi, if you don't mind, head over to GitHub page and open an issue there. We can continue the conversation and get you squared away. Cheers


I tried to install it, but running
AccountSummaryExample, matlab gives me an error (TWS has been started and Api activated):
>> addpath(path,pwd); addpath(path,fullfile(pwd,'docs'))
>> javaaddpath(fullfile(pwd,'Jar','TWS.jar'))
>> AccountSummaryExample
Undefined variable "com" or class "com.tws.Handler".

Error in TWS.Session (line 18)
this.handler = com.tws.Handler();

Error in TWS.Session.getInstance (line 94)
localInstance = TWS.Session();

Error in AccountSummaryExample (line 9)
session = TWS.Session.getInstance();

Because ?

Hamid Moazed

Siu Kei Lam

Ali Komai


Holger Pawlak

Abel Brown

@user12399 -- can you open issue over on the IB4m GitHub page? That way others can follow the conversation and will archive the result in case others have similar situation. Also, GitHub issue/questions go right to my email :)

No worries, specifying contracts in TWS can be a bit of an art depending on what you're looking for (e.g. FUT or OPT strike etc). Open an issue over at GitHub with a bit of code so I can reproduce and we'll get you sorted out. Cheers


thx for this toolset! finally making use of IBs historical data !

Q: I don't know how to (extract) specfic details after a ContractDetails request.
It is easy to access contract class variables (i.g. contract.m_symbol) but this one failed
Tried processing it with the collection2cell func. Still no result via (variablename).(variablename) scheme.

followed your guide, but unable do sth else then print them.

Abel Brown

Thanks for the feedback and good question.

You need to be subscribed to CBOE Index market data subscription in your IB account.

Once you have subscribed, then you can just make normal historical data query:

contract = com.ib.client.Contract();
contract.m_symbol = 'VIX' ;
contract.m_secType = 'IND' ;
contract.m_exchange = 'CBOE';
contract.m_currency = 'USD' ;

config.duration = '1 Y' ;
config.barsize = '1 day' ;
config.whatToShow = 'TRADES';
config.useRTH = 0 ; = 365 ;

requestId = round(rand*10000);

endDateTime = datestr(now(),'yyyymmdd 16:00:00');

session.eClientSocket.reqHistoricalData( ...
requestId ,...
contract ,...
endDateTime ,...
config.duration ,...
config.barsize ,...
config.whatToShow ,...
config.useRTH ,...
1 ,...
[] ...

Matlab Learner

Hi, thanks for putting the tool together. It is great. Can you tell me how I could get VIX reading from IB using your tool? Thanks.

Abel Brown

Hi Dave

IB4m uses sockets rather than the ActiveX. Currently using 9.72. Working on update to API 9.73

Dave Smith

Hi, thanks for building this tool. Can you tell me which version of the API it is using? 9.71 or 9.72? I also have the trading toolbox ib functions from matlab and cannot get that working presumably due to not supported version, but your version somehow works. Could you explain how that is? thank you.

Abel Brown

Hi Antti

Thanks for using IB4m.

TWS.Position and com.ib.client.ContractDetails are not related.

There are examples in the docs folder to show how to get contract details for an asset which you can then use to get list of expiry. See also the Options example in the docs folder as well.

Feel free to email with additional questions or open an issue over on Github.

Abel Brown

Hi Uri

The generic order factory is just as example to show how to create an order. You probably wouldn't use it to build your algo.

Orders are very simple, just create an order object and fill out the fields much like a struct()

order = com.ib.client.Order()
order.m_totalQuantity = 100

Then create contract the same way

contract = com.ib.client.Contract()
contract.m_symbol = 'IBKR';
contract.m_secType = 'STK';
contract.m_exchange = 'SMART';
contract.m_currency = 'USD';

Then place your order:


If you want to place a MOC order then simply change the order type to 'MOC'


Don't hesitate to email with additional questions or open an issue over at GitHub.

Uri Stein

Hi Abel, great job in getting this package together! It seems that you've added a generic market order to OrderFactory in the TWS package but the IB4m package does not recognize it. Can you please update the IB4m package with market as well as MOC orders? Thanks!

Antti Belt

Thanks a lot for this great package!

I just had a quick question: The class "position" only return symbol, position size and net value, but i would also like to know the expiry of the contract since i might have two different futures contract for the same symbol. is there a workaround for this? right now it seems in the java class file it only returns the symbol, not the entire contract details.


Abel Brown

Hi Wolfgang, Gateway connection should work with no problems. Double check IP and port. Be sure to select "IB API" on the connection screen. Shoot me an email and we can discuss if still an issue.

Wolfgang von Hessling

Great Job, works like a treat! However, so far I failed to connect via IB Gateway API, although I mirrored the API settings from IB TWS. Am I missing something? Many thanks

Eric Huang


Thanks! Great job!

John Moore

Abel Brown

Hi Anthony,

Glad you got it working!

Just as a reminder, you can call the "fields" method on the contract object to see all the available contract parameters. It is possible to think of GenericStockContract as essentially just a struct with some default field values .

Use the field "m_secType" to set the security type such as "STK", "OPT", "FUT", "IND" etc.

Check out IB API page for full contract details here:

If you want to send me a follow up message with your use-case details I will include it with the IB4m documentation/tutorials for other users.

Don't hesitate to follow up with additional questions or comments.


Hi, sorry fixed it, I had the contract.m_currency = 'EUR' defined before the contract = com.tws etc bit !!!!!! All works perfectly after I put it after




in other words, how to I modify the contract? You have a genericstockcontract but is there a more general form for say fx or index? Sorry if I have missed something obvious!!!



Hi Abel, its a basic question but how do I change the exchange or currency or other attributes to something other than the default settings when calling for historical or market data?




Abel Brown

Hi Alexey

Thanks for your feedback.

I'v added GenericMarketLimit to OrderFactory for convenience. Essentially, just set the orderType to "MKT" rather than "LMT". The limit price field has a default value of zero for market orders as advised in the IB API docs. Do a "git pull" to obtain the latest updates from github.

Don't hesitate to send an email if you have any additional questions/requests.


I'm sorry, missed your name Abel. my bad (:


Great upload Alex. Thanks. I'm new to Java and was looking into OrderFactory class and couldn't find how to place Market order instead of GenericLimitPrice. Could you please advise the right way?

Abel Brown

See for Quick Start Guide and documentation

MATLAB Release Compatibility
Created with R2016b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!