%% Implement a Financial Strategy by Using Stateflow
% This example shows how to use a standalone Stateflow(R) chart to model a
% financial trading strategy known as _Bollinger Bands_. Standalone charts
% implement classic chart semantics with MATLAB(R) as the action language.
% You can program the chart by using the full functionality of MATLAB,
% including those functions that are restricted for code generation in
% Simulink(R). For more information, see
% <docid:stateflow_ug#mw_d580cbaa-5437-4e23-a9b5-d7fd4fc42ff7>. 

% Copyright 2018-2020 The MathWorks, Inc.

%% Compute Bollinger Bands
% The Bollinger Bands trading strategy is to maintain a moving average of
% |N| stock prices for some commodity and issuing trading instructions
% depending on the value of the stock:
%
% * "Buy" when the value of the stock drops |K| standard deviations below
% the moving average.
% * "Sell" when the value of the stock rises |K| standard deviations above
% the moving average.
% * "Hold" when the value of the stock is within |K| standard deviations of
% the moving average.
% 
% Typical implementations for this strategy use values of |N| = 20 and |K|
% = 2.
%
% The file |sf_stock_watch.sfx| defines a standalone Stateflow chart that
% implements this financial strategy. The chart consists of two outer
% states in parallel decomposition.
%
% * The |StockTicker| subchart records the current price of a stock. The
% subchart hides the details for calculating stock prices. To access
% real-time market data from financial data providers, one possible
% implementation involves the use of the Datafeed Toolbox(TM). For
% details, see <docid:datafeed_doccenter#index>.
%
% * The |FinancialAdvisor| state uses the last |N| stock prices to compute
% high and low bands. Depending on the current price relative to these
% bands, the state generates "buy," "sell," or "hold" instructions. The
% action |on every(1,sec)| creates a MATLAB(R) timer to execute the chart
% every second. See <docid:stateflow_ug#f0-34084>.
%
% Parallel decomposition is a common design pattern that enables your
% algorithm to preprocess input data. For more information, see
% <docid:stateflow_ug#bu_4225-1>.

% Set up charts with white background
set_param(0,'ExportBackgroundColorMode','white');

edit sf_stock_watch.sfx

%% Execute Standalone Chart
% To execute the standalone chart, create a Stateflow chart object |w|:
%
%   w = sf_stock_watch();
%
% The chart generates a stream of stock prices and issues "buy," "sell," or
% "hold" instructions.
%
%  Note: Chart execution continues until you delete the chart object.
%  Loading data... Ready in 5 4 3 2 1 0: 
%  HOLD at 14.1942
%  SELL at 14.2802
%  SELL at 14.247
%  HOLD at 14.2025
%  BUY at 14.1444
%
% To stop the chart execution, delete the chart object w:
%
%   delete(w);