Code covered by the BSD License  

Highlights from
Nested Function Live Stock Ticker

from Nested Function Live Stock Ticker by Scott Hirsch
An example using nested functions and WSDL to create a live stock-ticker.

nested_timer_ex
function nested_timer_ex
%% NESTED_TIMER_EX  Example of using nested functions for a timer callback
% NESTED_TIMER_EX embeds a stock ticker in your MATLAB Desktop
%
% This application uses a WSDL web service to provide live (albeit 20
% minute delayed) stock quotes.  By using a MATLAB timer object, it runs
% continuously as a background task (without blocking the MATLAB command
% line).
%
% This application is not meant to be a serious stock ticker - it is
% intended to highlight usage of nested functions.  If you really need to
% get live stock prices into MATLAB, please use the Datafeed Toolbox.
%
% 1/6/2010: The web service used by this example is no longer available.

% Scott Hirsch
% shirsch@mathworks.com
% Copyright 2005-2010 The MathWorks, Inc

%% User Configurable Parameters
UpdateRate = 5;                 % How often to get new values (s)
NValuesMax = 20;               % Display axes width (in values, not seconds)
DefaultStockSymbol = 'GOOG';    % Default Stock ticker symbol


%% Create timer object
% We use a timer object to have MATLAB fetch the latest stock price at a
% fixed interval.  The callback function is a nested function, myCallback
t = timer;
t.ExecutionMode = 'fixedRate';
t.Period = UpdateRate;
t.TimerFcn = @myCallback;       % Handle to nested callback function below

%% Initialize graphics
% Build a lightweight user interface

% Create a docked figure.  Use a custom CloseRequestFcn to stop and delete
% the timer before closing.
hFig = figure('WindowStyle','docked','CloseRequestFcn',@closeFunction);

% Add text and and edit box for specifying the ticker symbol
hTickerText = uicontrol(hFig,'style','text','pos',[20 20 50 20],'string','Symbol:');
hTickerEdit = uicontrol(hFig,'style','edit','pos',[70 20 50 20 ], ...
    'string',DefaultStockSymbol,'BackgroundColor','white', ...
    'Callback',@myCallback);
% Note that updating the ticker symbol has the same behavior as the timer.

% Draw a blank line.  We'll replace it with live values as they come in.
time = (0:1:NValuesMax-1)*UpdateRate;
hLine = plot(time,NaN*ones(NValuesMax,1));
xlabel('s'); ylabel('$')

ind = 0;        % Initialize counter for plot update
drawnow         % Force a graphics draw before the timer starts

%% Start timer
start(t)        % This will call myCallback every UpdateRate seconds

    function myCallback(varargin)
        %myCallback  Callback function for stock ticker timer object
        %Don't bother specifying input arguments explicitly, since we don't
        %need them (but they are required by timer object).

        % Get quotes
        StockSymbol = get(hTickerEdit,'String');    % Current ticker symbol
        try
            price = localGetQuote(StockSymbol);     % Use WSDL service to get stock quote
        catch
            error(['Could not retrieve price for ' StockSymbol])
        end


        % Update display.  Replace values of hLine with latest stock prices
        ind = rem(ind+1,NValuesMax);if ind==0, ind=NValuesMax; end; % Increment index
        yd = get(hLine,'YData');
        yd(ind) = price;
        set(hLine,'YData',yd)
        title(['Stock Price: ' StockSymbol])

    end     % function myCallback

    function closeFunction(varargin)
        % closeFunction    CloseRequestFcn for stock ticker figure.

        % Stop and delete timer
        stop(t)
        delete(t)

        % Delete the figure
        delete(hFig)
    end

end     % function nested_timer_ex



function value = localGetQuote(symbol)
% LOCALGETQUOTE  Get stock quote
% LOCALGETQUOTE(SYMBOL) Gets a 20 minute delayed stock quote for SYMBOL

% localGetQuote is provided as a local function instead of a nested
% function because it doesn't really need general access to data in the
% main function.  It works well as a traditional function, with clearly
% defined input and output.

% Create the WSDL file if necessary
wsdlFile = 'DelayedQuotesService.wsdl';
wsdlUrl = 'http://services.xmethods.net/soap/urn:xmethods-delayed-quotes.wsdl';
if ~(exist(wsdlFile,'file') == 2)
    try
        urlwrite(wsdlUrl,wsdlFile);
    catch
        error('Unable to create WSDL file for DelayedQuotesService.wsdl');
    end
end

% Create class from WSDL file if necessary
if ~(exist('@StockQuoteService','dir') == 7)
    try
        % Create class from WSDL
        createClassFromWsdl(wsdlFile);
    catch
        % Throw error
        error('Unable to create WSDL class for StockQuoteService');
    end
end


sqs = StockQuoteService;            % Create StockQuoteService object
value = getQuote(sqs,symbol);       % Get current stock value
end % function localGetQuote

Contact us at files@mathworks.com