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

  • How Google Develops New Managers
    Alex Langshur, host of Google Partners Podcasts, has organized the podcast Google HR secrets: identifying & developing great managers, interviewing Sarah Calderon, People Development at Google, on how Google selects, trains, and develops their managers. By Abel Avram
  • Presentation: Cognitive Services, Next Step in Creating Our Robot Overlords
    Harold Pulcher discusses Cognitive Services, how to get started using them, and how to incorporate speech, image, and facial recognition into an application. By Harold Pulcher
  • Presentation: Control Flow Integrity Using Hardware Counters
    Jamie Butler and Cody Pierce discuss a new system for early detection and prevention of unknown exploits. Their system uses Performance Monitoring Unit hardware to enforce coarse-grained Control Flow Integrity (CFI). They intend to prove that their approach is effective and suitable for practical use, while staying resistant to bypass. By Jamie Butler
  • JetBrains Launches GoLand Go IDE
    JetBrains has moved its Go IDE from its early access programme to market. Now branded as GoLand, the IDE extends the IntelliJ platform making its core functionality specific to Go. This follows suit with their other language-specific tools such as PyCharm for Python and RubyMine for Ruby. By Andrew Morgan
  • Panel on the Future of AI
    An SF QCon panel on the future of AI explored some issues facing machine learning today. The areas explored: critical issues facing AI right now, how has technology changed the way people are hired, how non-leading edge companies make the best use of current technologies, what the role of humans in relation to AI is, and exciting new breakthroughs on the imm […]
  • Microsoft Updates Cosmos DB with Cassandra Support and Provides Better Availability Guarantees
    Last month at Microsoft Connect 2017, Azure Cosmos DB received several new updates, including support for using the Cassandra NoSQL database API and increased guarantees for availability. With the Cassandra NoSQL database API, customers can run operations inside Cosmos DB on a data model. The availability guarantee moves from 99.99 percent to 99.999 percent. […]
  • Article: Approximate Computing on WSO2: Explaining Approximation Algorithms in an Applied Setting
    In this article, we describe an example real world application of API monitoring which gets benefit by using approximate stream processing. We developed the application on top of WSO2 Stream Processor as Siddhi extension. Siddhi is the complex event processing library which acts as the event processing engine of WSO2 Stream Processor. By Chamod Samarajeewa
  • Rust in Visual Studio and VS Code
    Daniel Griffen has released a preview version of a Rust language service for Visual Studio. This plugin requires Visual Studio 2017 Preview, an experimental release stream for testing new VS features. By Jonathan Allen
  • Article: Key Takeaway Points and Lessons Learned from QCon San Francisco 2017
    The eleventh annual QCon San Francisco was the biggest yet, bringing together over 1,800 team leads, architects, project managers, and engineering directors. By Abel Avram
  • Article: Q&A With Eberhard Wolff On the Book “A Practical Guide to Continuous Delivery”
    Eberhard Wolff speaks with InfoQ about his work "Continuous Delivery: A Practical Guide", where we detail some of the major concepts behind successful CD adoption and the ripple-effect it can have on developer productivity and quality of service. By Dylan Raithel

 

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: