A standalone Stateflow® chart is a MATLAB® class that defines the behavior of a finite state machine. Standalone charts implement classic chart semantics with MATLAB 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®. For more information, see Create Stateflow Charts for Execution as MATLAB Objects.
This example shows how to use a standalone Stateflow chart to model a financial trading strategy known as Bollinger Bands. The 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.
sf_stock_watch.sfx defines a standalone Stateflow chart that implements this financial strategy. The chart consists of two outer states in parallel decomposition.
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™. For details, see Datafeed Toolbox.
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® timer to execute the chart every second. See Control Chart Execution by Using Temporal Logic.
Parallel decomposition is a common design pattern that enables your algorithm to preprocess input data. For more information, see State Decomposition.
To execute the standalone chart, create a Stateflow chart object
w with the configuration option
'-warningOnUninitializedData' set to
w = sf_stock_watch('-warningOnUninitializedData',false);
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
wfrom the MATLAB workspace: