DotNet

How to show Stock Market prices in WPF UI?


 

I developed a sample application long time back to use WPF UI in multithreaded scenario. This application shows market prices in real time. I don’t have any exchange connection so I created arbitrary market price generator to simulate live environment. I am explaining step by step functionality of this application which is covering following topics:

  1. Use of delegates and events.
  2. Use of WPF controls.
  3. Marshals call from different thread to UI thread
  4. Use of ObservableCollection Object.
  5. Use of Task library (Parallel Programming).

This sample has Following classes:

  • MarketData: entity class to encapsulate properties of market price of stock.
  • MarketDataProvider: this class is generating market price and sending events.
  • MarketWatch.Xaml: WPF UI class which is showing market prices in grid.

MarketData.cs

It is having below properties:

namespace MarketWatchApp
{
    public class MarketData
    {
        public string Symbol
        {
            get;
            set;
        }
        public decimal LastPrice
        {
            get;
            set;
        }
        public decimal PriceChange
        {
            get;
            set;
        }
        public decimal ClosePrice
        {
            get;
            set;
        }
        public decimal OpenPrice
        {
            get;
            set;
        }
    }
}

Delegate MarketDataHandler

It’s signature has parameter as MarketData object. This delegate is using for callback Market prices to UI.

public delegate void MarketDataHandler(MarketData price);

MarketDataProvider.cs

This class has instance of event which is encapsulating delegate MarketDataHandler.

Method: GenerateMarketData is generating arbitrary prices for stock and then sending notifications in events.

 public class MarketDataProvider
    {
        public event MarketDataHandler OnMarketData;
        private readonly Random random = new Random();
        private bool _stop;

        public bool Stop
        {
            get { return _stop; }
            set { _stop = value; }
        }

        public void GenerateMarketData()
        {
            //start
            MarketData InitialPrice = new MarketData();
            decimal closeprice = 0M;
            decimal openPrice = 0M;
            openPrice = Math.Round(Convert.ToDecimal(Gaussian()), 2);
            closeprice = openPrice - 1;
            InitialPrice.Symbol = "IBM";
            InitialPrice.OpenPrice = openPrice;
            InitialPrice.ClosePrice = closeprice;
            InitialPrice.LastPrice = openPrice;

            if (OnMarketData != null)
                OnMarketData(InitialPrice);

            InitialPrice = new MarketData();
            InitialPrice.Symbol = "MSFT";
            InitialPrice.OpenPrice = Convert.ToDecimal(Gaussian());
            InitialPrice.ClosePrice = InitialPrice.OpenPrice-1;
            InitialPrice.LastPrice = Math.Round(Convert.ToDecimal(Gaussian()), 2);
            InitialPrice.PriceChange = InitialPrice.LastPrice - openPrice;

            if (OnMarketData != null)
                OnMarketData(InitialPrice);

            for (int i = 0; i < 1000; i++)
            {
                InitialPrice = new MarketData();
                InitialPrice.Symbol = "IBM";
                InitialPrice.OpenPrice = 34.56M;
                InitialPrice.ClosePrice = 34.45M;
                InitialPrice.LastPrice = 34 + Math.Round(Convert.ToDecimal(Gaussian()), 2);
                InitialPrice.PriceChange = InitialPrice.LastPrice - InitialPrice.OpenPrice;

                if (OnMarketData != null)
                    OnMarketData(InitialPrice);

                InitialPrice = new MarketData();
                InitialPrice.Symbol = "MSFT";
                InitialPrice.OpenPrice = 54.56M;
                InitialPrice.ClosePrice = 54.45M;
                InitialPrice.LastPrice = 54 + Math.Round(Convert.ToDecimal(Gaussian()), 2);
                InitialPrice.PriceChange = InitialPrice.LastPrice - InitialPrice.OpenPrice;

                if (OnMarketData != null)
                    OnMarketData(InitialPrice);

                InitialPrice = new MarketData();
                InitialPrice.Symbol = "DB";
                InitialPrice.OpenPrice = 20.45M;
                InitialPrice.ClosePrice = 20.40M;
                InitialPrice.LastPrice =20+ Math.Round(Convert.ToDecimal(Gaussian()), 2);
                InitialPrice.PriceChange = InitialPrice.LastPrice - InitialPrice.OpenPrice;

                if (OnMarketData != null)
                    OnMarketData(InitialPrice);

                
                Thread.Sleep(100);
                
                if (_stop)
                    break;
            }

        }
        private string GenerateFakeMarketData()
        {
            return "CSCO " + string.Format("{0:##.##}", 22 + Math.Abs(Gaussian()));
        }

        private double Gaussian()
        {
            double x1, x2, w;

            do
            {
                x1 = 2.0 * random.NextDouble() - 1.0;
                x2 = 2.0 * random.NextDouble() - 1.0;
                w = x1 * x1 + x2 * x2;
            } while (w >= 1.0);

            w = Math.Sqrt(-2.0 * Math.Log(w) / w);

            // two Gaussian random numbers are generated
            return x1 * w;
            //y2 = x2 * w; 
        }
    }

 

MarketWatch.xaml

It is WPF UI class which has datagrid with columns Symbol, Last price, close price etc for any stock.

I have used ObservableCollection collection object which represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.

Constructor of this class is doing following actions:

  • Creating instance of MarketDataProvider class.
  • Creating instance of ObservableCollection
  • setting DataContext of datagrid to observableCollection object
  • Subscribe event (OnMarketData) of MarketDataProvider class.
	public MarketWatch()
        {
            InitializeComponent();
            provider = new MarketDataProvider();
            marketdatalist = new System.Collections.ObjectModel.ObservableCollection();
            dataGrid2.DataContext = marketdatalist;
            provider.OnMarketData += new MarketDataHandler(provider_OnMarketData);
        }

Consuming event (OnMarketData)

Method "provider_OnMarketData": is getting price in "MarketData" object. “Dispatcher.CheckAccess" method is to determine whether a thread has access to a control of UI. In this case event generated from different thread other than UI thread so it will always return false. Use Invoke or BeginInvoke to access the object from a different thread. Actually These methods will marshal call from different thread to UI thread.

Invoke: Marshall call to UI thread synchronously.

BeginInvoke:Marshall call to UI thread asynchronously

Dispatcher.Invoke method expects parameter as delegate.

Here I used anonymous method to add or update MarketData object in “marketdatalist” ObservableCollection object. Marketdatalist object is automatically notifying grid about change in underlying data and grid automatically update respective row with latest data.

  void provider_OnMarketData(MarketData price)
        {
            if (!this.Dispatcher.CheckAccess())
            {
                this.Dispatcher.Invoke(
                    new Action(delegate()
                        {
                            int indx = _list.FindIndex(delegate(MarketData row) { return row.Symbol.Equals(price.Symbol); });
                            if (indx == -1)
                            {
                                _list.Add(price);
                                marketdatalist.Add(price);
                            }
                            else
                            {
                                _list[indx] = price;
                                marketdatalist[indx] = price;
                            }
                        }));

                return;
            }
        }

 

Method: Button_Click

New task is created and running “provider.GenerateMarketData()” method asynchronously.

Task.Factory.StartNew(() => provider.GenerateMarketData());

Run Application

  1. Compile Source code and then run MarketWatchApp.exe.
  2. Click “Start Market” button.

 

image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s