Click here to Skip to main content
Click here to Skip to main content

Simple Real-Time Ticker Using C# / NET / WCF / WPF

By , 1 Oct 2008
 

Introduction

This is a simple working Real-Time data publisher written in C# NET 3.5. It is composed of two pieces, a server WCF console and a WPF client. It demonstrates a simple way of maintaining a persisted callback to multiple clients. Each client subscription is maintained by the server console.

The code demonstrates an implementation of the following:

  • Publish / Subscribe Implementation (not events)
  • ClientCallback subscription
  • Fake Tick Plant
  • Data Dictionary
  • Multi-Threading
  • Object Serialization

Overview Class Structure

How to Run

There are two working executables in this project, a WCF console (WCFMarketDataServer.exe) and a WPF client (WFCTickerWindow.exe).

First start the WCF console. You can only have one instance running. The server is ready once you see the "press any key" prompt:

WCF Console

Now you can start the client. You can start as many clients as you want to simulate multiple users. Each client should maintain its own set of real time data.

WPF Client

As you change the preset value on the combo boxes, a subscription / un-subscription requests will be processed by the server to maintain the proper data each to which each client is subscribed.

Using the Code

Below, find an overview of the main class structure. I am not going into much detail but it shows how the main data flows and the subscription mechanism is working.

Detailed Class overview

The WCF server console is configured programmatically utilizing a TCP channel.

    // Service htpp address
    CMarkerConfig.LogInfo("Creating URI...");
    Uri baseAddress = new Uri("net.tcp://localhost:8080/MarketData");

    // Create new WCF Service host
    CMarkerConfig.LogInfo("Creating ServiceHost...");
    serviceHost = new ServiceHost(typeof(CMarketDataManager), baseAddress);


    // Add the htpp end point 
    NetTcpBinding pNetTcpBinding = new NetTcpBinding(SecurityMode.Transport);


    CMarkerConfig.LogInfo("Adding Endpoint...");
    serviceHost.AddServiceEndpoint(typeof(IMarketData), pNetTcpBinding, baseAddress);

    // Add the Metadata
    CMarkerConfig.LogInfo("Adding Metadata behavior...");
    ServiceMetadataBehavior servicemetadatabehavior = new ServiceMetadataBehavior();
    servicemetadatabehavior.HttpGetEnabled = true;
    servicemetadatabehavior.HttpGetUrl = new Uri("http://localhost:8081/MarketData");
    serviceHost.Description.Behaviors.Add(servicemetadatabehavior);

Following is the service contact:

    //----------------------------------------------------------------------------------
    /// <summary>
    /// Callback contract to update clients with TickUpdate data stream.
    /// </summary>

    interface IClientCallback
    {
        //-------------------------------------------------------------
        [OperationContract(IsOneWay = true)]
        void SendTickUpdate(TickUpdate pTickUpdate);
    }

    //-----------------------------------------------------------------------------------
    /// <summary>
    /// WCF Contracts for client interaction with this service
    /// </summary>
    [ServiceContract(Namespace = "tcp://localhost/", CallbackContract = typeof(
        IClientCallback))]
    interface IMarketData
    {
        //-------------------------------------------------------------
        [OperationContract]
        string[] GetSymbolList();

        //-------------------------------------------------------------
        [OperationContract]
        StringCollection GetDataSourceList();

        //-------------------------------------------------------------
        [OperationContract]
        string[] GetFieldList();

        //-------------------------------------------------------------
        [OperationContract]
        void SubscribeRT(CGenericMsg pCGenericMsg);
    }

All data updates are sent via IClientCallback implemented by the WPF client.

The method SubscribeRT() is designed to take a CGenericMsg object. This object is generic so multiple types of messages can be added without having to change the contract.

Points of Interest

This sample helped me better understand what WCF and WPF are all about. It is a good introductory project into the frameworks for an intermediate developer.

I hope someone can benefit from it at some level as much as I did.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Carlos A Alvarez
Windows Consultant
United States United States
Member
20+ yrs Leading and Developing Microsoft products in the Financial Industry.
 
My main background is VC++, server and client development.
 
Currently focused in WPF/XAML, Windows 8 and Windows Azure Server technologies.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionExcellent code but poor article explanationmemberDavid Zenou27 Dec '11 - 0:37 
Cry | :((
Si tu aimes ce que tu fais , tu finis par réussir !
(french proverb of David Zenou)

QuestionMake the client run on android or iOSmemberBenjamin Krause6 Dec '11 - 0:38 
Hi, is it somehow possible to port the client for other (mobile) devices?
AnswerRe: Make the client run on android or iOSmemberCarlos A Alvarez7 Dec '11 - 6:21 
No, unless they magically support WPF Smile | :) .. Funny you mentioned, I am thinking on rewriting it with client in HTML5.
GeneralRe: Make the client run on android or iOSmemberBenjamin Krause7 Dec '11 - 6:47 
Is that even possible with HTML5? I would love to see that... :p
Questionconect-reconnect on failure?memberMikeKosak16 Oct '11 - 5:18 
I am seraching for an implementation that covers what to do when you lose your conection
 
For example- when the server goes down and is restarted or the internet cable is yanked out.. etc..
AnswerRe: conect-reconnect on failure?memberCarlos A Alvarez17 Oct '11 - 3:01 
The latest WCF has some re-connect functionality you can consider. Although you could easily add a layer to monitor a "heartbeat", and reconnection logic, into the communication layer.
GeneralCloud Hosted?membernz_ham23 May '11 - 17:50 
Excellent article!
Just a question if I can, would this be able to be hosted in Windows Azure as it stands? If not, what considerations would you be looking at?
Cheers
GeneralRe: Cloud Hosted?memberCarlos A Alvarez17 Oct '11 - 2:59 
I have not tried it but you could host it in Azure as worker services. Remember it is subscription based so you would have to deal with state management on the publisher side.
Generalsolution is missing reference to WCFMarketDataSharedmembercybNeo26 Jan '11 - 8:19 
I'm using VS Team 08 on a win 2008 server R2. i downloaded the solution and its missing a reference to WCFMarketDataShared, also getting a compile error on Microsoft.Common.targets "CustomBeforeMicrosoftCommonTargets".
 
Am I missing something?
QuestionWould you mind sharing some performance insight?membersdai10 Dec '09 - 9:37 
Great article and thank you very much for sharing.
I was too working on a market data related product but it was written in COM.
I assume that you might have implemented some kind of realtime server in WCF. If so, I was wondering if you could share some insight as whether the performance is up to the standard of using c++.
If so, are you going to replace the old ones?
Thank a lot again.
AnswerRe: Would you mind sharing some performance insight?memberWayne Walter19 Dec '09 - 10:41 
The implementation in this article will be sufficient for to keep up with
real time data feed on a few symbols of Level 1 data. But WCF callbacks will
be far too slow to keep up with 1,000s of symbols and Level II, order book data.
 
For the TickZoom system for historical testing and fully automated trading,
it was necessary to build a custom protocol to achieve performance required.
 
You ask about comparing to C++. I'm a C++ programmer now working with C#.
C# is wonderfully easy to write in the parts like initialization where performance
isn't a concern. When you get to critical path code like this, C# allows
unsafe code with pointers and allows PInvoking to C and C++ native APIs.
 
I personally found the built-in classes that make TCP/IP "easy" in .NET were
far, far too slow for trading performance needs. So I build my own high performance
classes built on calling Winsock2 native API directly.
 
Remember, C# gets compiled to machine code just like C++ except that C# is JIT
compiled where C++ is precompiled. So there's no difference between the speed the
languages can operate on problems like this. The only thing that differs is skill
between developers.
 
Sincerely,
Wayne
AnswerRe: Would you mind sharing some performance insight?membersdai23 Dec '09 - 11:07 
Thank you very much for the detailed information.
Sorry I didn't reply soon enough. I checked the site in the first several days after I posted the message and I didn't get an answer so I didn't check it afterwards until now.
From what you said, I got an impression that you meant the performance gain by using c++ is really from building your own customized protocols and/or possibly accessing the lower tcp/ip level functions and other lower level system APIs I assume.
Also, say in an ordinary case where there is no use of low level access, are you saying that a fairly large scaled c# application could have the similar performance as c++ counterpart since they are eventually translated to the similar sets of machine codes? If that is true, the bianries from c++ and that of c#, say using precompiled, not IL version should be similar in size and content?
Sorry for these questions but I am looking for the answers from a while.
Thanks again and merry christmas and happy new year.
Steven
GeneralRe: Would you mind sharing some performance insight?memberWayne Walter23 Dec '09 - 12:50 
Often the IL code of C# takes less space than a C++ precompiled since many of the IL codes must be translated to multiple machine code instructions. IL is slightly higher level instruction set than most CPUs offer.
 
If you start to compare C++ to C# in other areas besides just speed, C++ loses completely. The major area are tools that simplify programming including, most notably, automated unit testing. The tools like NUnit and TypeMock that are available for C# for automated testing blow away what you can do in C++. Much of that has to do with C# having reflection features like Java.
 
So if you're doing anything on Windoze, C# wins, for sure. For Linux, C# runs does on Linux using Mono and is binary compatible. However, therein lies a paradox since M$ isn't too thrilled about Linux, there aren't as good of development IDE's on Linux for C#. But the compiled programs are binary compatible as long as your code either:
 
1. Never uses any O/S APIs directly <--- which severely limits your ability to get great performance or ..
2. Make a low level library for O/S calls like WinSock2 on WinDoze and Berkely sockets on Linux. So that when you switch O/S, you simply load a different dll wrapper for each O/S.
 
Finally, if you want a GUI with your app, you have to decide whether to use a graphics library that works on both Linux or Windows which makes your app seam a little lame on Windows or do one of the following.
 
Smart developers who must support both Windows and Linux but need a great-looking Windows GUI can build their apps either with MVC or MVVM design so that it's easy to "skin" the app and have a Linux friendly skin which can be straightforward if you keep the Skin or "view" code separate from the Model and Controller code and make sure those parts of pure C# and O/S independent.
 
The other option is our choice at TickZoom and the customers of TZ, that is, build a Windows GUI for monitor and control but all the high speed server component which don't need a GUI can be run on both WinDoze or Linux.
 
Well, that's my treatise on C# vs C++.
 
Wayne
AnswerRe: Would you mind sharing some performance insight?membersdai23 Dec '09 - 14:31 
Thank you very much for your insight.
I guess that if one day c# or java ran as fast as c++, most of c++ programmers would lose our jobs.
But for now, I will have to learn both which is not necessarily a bad thing.
Thanks again.
Steven
GeneralThanks for sharingmemberMember 456543328 Oct '09 - 10:42 
I have no problems with WPF/WCF, was just looking for a "real-time" streamer, this ones help no end.
 
thank you.
 
Got my 5
GeneralExcellent Articlemembergil66618 Oct '09 - 21:33 
Excellent solution
GeneralREAL TIME SCHEDULING SYSTEMmemberrikki2337527 Oct '09 - 2:57 
Hi


I am trying to create a system in india which is on similar lines with http://twilio.com for which i require efficient engineers working on it.I want to create something like this in asterisk .It will be grateful if you can mail me your technical know how and how you will making this system(language etc).So that i can think of hiring you for this system
GeneralExcellent ! Thanks!memberokcode12 Jun '09 - 19:46 
Excellent ! Thanks!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 1 Oct 2008
Article Copyright 2008 by Carlos A Alvarez
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid