Technology Corner

Home » DotNet » How to show Stock Market prices in WPF UI?

How to show Stock Market prices in WPF UI?

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 80 other followers

Twitter updates

Archives

RSS InfoQ Feeds

  • Article: Q&A on the Book "Humans vs Computers"
    Author Gojko Adzic has released a book, Humans vs Computers in which he tells stories about the impact of inflexible automation, edge cases and software bugs on the lives of real people. He explains the common mistakes built into the systems and provides advice on how to prevent these mistakes from being built into our systems in the first place. By Shane Ha […]
  • Q&A with Michael Coté on Devops Adoption and his Talk at DevOpsDays NZ
    Raf Gemmail talks to Pivotal’s Michael Coté about obstacles to DevOps adoption and his forthcoming talk at DevOpsDays NZ 2017 By Rafiq Gemmail
  • TensorFlow Serving 1.0 Release Detailed at Google I/O
    Google's Noah Fiedel details new programming model for TensorFlow Serving in a stable 1.0 release. Subject matter addresses common challenges with portability, servablility , and reproducibility improvements. By Dylan Raithel
  • First NetBeans Code Drop Lands at Apache
    Oracle has released the first of three NetBeans code drops to the Apache Incubator. By Matt Raible
  • Article: The Top 10 Adages in Continuous Deployment
    On the basis of discussions at the Continuous Deployment Summit, researchers derived 10 adages about continuous-deployment practices. These adages represent a working set of approaches and beliefs that guide current practice and establish a tangible target for empirical validation. By Chris Parnin
  • Podcast: Joshua Kerievsky and Heidi Helfand on High Performance via Psychological Safety
    In this podcast Shane Hastie, Lead Editor for Culture & Methods, spoke to Joshua Kerievsky, CEO of Industrial Logic, and Heidi Helfand, Director of Engineering Excellence at Procore Technologies and author of the book Dynamic Reteaming, about their talk High Performance via Psychological Safety. By Joshua Kerievsky
  • Spotify and Google Release Forseti GCP Security Tools
    Google has opened up Forseti Security, a set open source tools for GCP security, to all GCP users. The project is the result of a collaborative effort from both Spotify and Google, combining what was originally separate work together into a single toolkit. It aims to automate security processes for developers in order for them to develop more freely. By Andr […]
  • Article: Q&A on the Book SAFe Distilled
    The book SAFe Distilled breaks down the complexity of the framework into easily understood explanations and actionable guidance. It’s a resource for acquiring a deep understanding of the Scaled Agile Framework, and how to implement it successfully. By Ben Linders
  • String Interpolation in Entity Framework Raises Concerns
    One of the new features in Entity Framework Core 2 is the ability to automatically convert interpolated strings into parameterized SQL. Though designed to avoid problems with poorly written SQL, it is feared that it may actually lead to more SQL injection attacks. By Jonathan Allen
  • Podcast: Twitter's Yao Yue on Latency, Performance Monitoring, & Caching at Scale
    Yao Yue spent the majority of her career working on caching systems at Twitter. She created a performance team that deals with edge performance outliers often exposed by the enormous scale of Twitter. In this podcast, she discusses standing up the performance team, thoughts on instrumenting applications, and interesting performance issues (and strategies for […]

 

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

Blogs I Follow

%d bloggers like this: