%% Money.Net Data Workflow Example

%   Copyright 2016 The Mathworks Inc.

%% Connect to Money.Net
c = moneynet(username,password);

%% Obtain current data from a symbol 
sec = 'IBM'; % retrieve data from IBM(R)
fields = {'Description','Ask','Bid'}; % retrieve data regarding the description, ask ,and bid prices

%Fetch and display the current data
currentData = getdata(c,sec,fields); 
disp(currentData);

%% Obtain current data from multiple symbols
secs = {'IBM','MSFT','YHOO','GOOG','AAPL'};
currentData = getdata(c,secs,fields); 
disp(currentData);

%% Obtain timeseries data from a symbol
date = [datetime('today') - days(30), datetime('today')]; %retrieve data starting from 30 days ago to today
interval = '1D'; %retrieve end-of-day data at one-day intervals

%Fetch and display timeseries data
timeseriesData = timeseries(c,sec,date,interval);
disp(timeseriesData);

%% Obtain options from a symbol

% Fetch option symbols for the symbol of interest
options = optionchain(c,sec);

%Display the first 10 option symbols
disp(options(1:10));

%Use GETDATA to retrieve more information about the options
fields = {'Description','Strike','Expiration','Ask','Bid'};
optionData = getdata(c,options,fields);

%Sort the table by expiration date and strike price
optionData = sortrows(optionData,{'Expiration','Strike'});

%Display the first 10 rows of option data
disp(optionData(1:10,:));

%% Subscribe to real-time data updates

% Subscribe to real-time updates for the symbol using the default event
% handler (A variable containing real-time data will be created in the
% MATLAB Workspace)
realtime(c,sec);

% Unsubscribe from the real-time data updates for the symbol
stop(c,sec);

% Use a custom event handler function to view or process real-time data
% updates
realtime(c,sec,@(x)disp(x)) % Display individual updates on the Command Window as the become available

% Unsubscribe from the real-time data updates for the symbol
stop(c,sec);

%% Close the connection to Money.Net
close(c);
