MATLAB: How to get data from new stocks with an existing Bloomberg connection

bloombergblpDatafeed Toolboxhistory

I have an existing Bloomberg connection, which I queried with 'realtime'. I have some new stocks that I want to also look up, without having to close the connection and re-add the original stocks. My code is like this:
b= blp;
fields = {'Last_Trade','Volume'}
[subs,t] = realtime(b,'IBM US Equity',fields);
newStocks = {'MSFT US Equity';'AAPL US Equity'};
[subs,t] = realtime(b,newStocks,fields);
On the last line, MATLAB hangs. How can I get MATLAB to not hang, and return 'Last_Trade' and 'Volume' for both IBM and Microsoft?

Best Answer

To do this, you can make use of the underlying Bloomberg API. This looks like the following:
% Initial setup
b= blp;
fields = {'Last_Trade','Volume'}
fStock = {'IBM US Equity'}
[subs,t] = realtime(b,fStock,fields);
newStocks = {'MSFT US Equity';'AAPL US Equity'};
% Import some of the API libraries into the script
import com.bloomberglp.blpapi.*;
% Create a string representation of all of the fields we are requesting
% This is needed later when we add new tickers
fieldsChar = strjoin(fields,',');
% Unsubscribe our connection without completely closing it/
% re-requesting data
b.session.unsubscribe(subs)
% Using the blpapi, add each of the new tickers as subscriptions to
% the original subscription.
% Makes use of the Subscription object, which only takes a single
% string as input, thus requiring the for loop
% Note the different format than the input to the realtime method
for nt = 1:numel(newStocks)
subs.add(Subscription(newStocks{nt},fieldsChar,'',CorrelationID(newStocks{nt})));
end
% Resubscribe, now that the new tickers have been added
b.session.subscribe(subs)