Sunday, May 10, 2015

SignalR-based Live Stock Ticker with Ticker.FSharp

Introduction

It was an awesome weekend, finally got my hands into SignalR and updated the Ticker.FSharp to add a SignalR web sample ticker. In this post I have talked about how easy it was to throw a simple ticker together using the Ticker.FSharp repository and SignalR. The sample can be downloaded from the Github repository page.

Screenshot





Implementation

I added an empty web project to the solution, then added a SignalR Hub, a Javascript file for event handling, an HTML page for the UI. Here is a quick overview of each of those.

SignalR Hub

As we know, the server-side hub is a primitive component of a SignalR application. My sample hub has only two methods, one is called by the client to start up the hub when it gets launched the first time, and other method is called from the server side that reports the ticks generated by Ticker.FSharp. The call to Tick then channels in to the browsers of each user connected.

The full source listing for the hub file can be found at this Github page. I am only discussing the important points.

Here is how the Hub is declared

[HubName("tickerFsharp")] public class TickerFSharpHub : Hub
As you can see, the hub declaration contains the HubNameAttribute which tells the SignalR engine how the hub is going to be located. There are two methods inside the hub, one is StartTicker which is responsible for calling the Ticker.FSharp library and obtaining the IObservable<Tick> object. Here I am fetching the ticks of three symbols together.

[HubMethodName("startTicker")]
public void StartTicker()
{
if (subscription == null)
{
var machine = new DataMachine();
var aapl = this.AddIndicator(machine.GetLiveGoogleApiTicks("AAPL"));
var goog = this.AddIndicator(machine.GetLiveGoogleApiTicks("GOOG"));
var msft = this.AddIndicator(machine.GetLiveGoogleApiTicks("MSFT"));

subscription = aapl.Merge(msft).Merge(goog).Subscribe(t => {

this.Tick(t.Tick.Symbol, t.Tick.Price, t.Tick.LastUpdated.ToString(), t.Up);

});.
}

In the above listing, I am calling the Ticker.FSharp 3 times to get the live feed for three symbols. I am also calling the AddIndicator helper method to garnish the object with an additional property that tells me whether the value went up or down since the last value. And finally, I am calling the Tick method which calls the tick method at the client's side.

public void Tick(string symbol, double price, string lastUpdated, bool up)
{
Clients.All.tick(symbol, price.ToString("###0.00"), lastUpdated, up);
}

The above Tick() method implementation is pretty self-explanatory.

Javascript Event Handling

The JS file has quite the code, I am only discussing the tick() handler that server-side will be calling.

hub.client.tick = function (symbol, price, lastUpdated, up) {
var row = $stockTableBody.find("tr[datasymbol=\"" + symbol + "\"]");
if (row.length == 0) {
var templatedRow = rowTemplate.replace("{Symbol}", symbol)
.replace("{Price}", price)
.replace("{lastUpdated}", lastUpdated);
$stockTableBody.append(templatedRow);
}
else {
var cells = row.first().find("td");
cells.eq(0).html(symbol);
cells.eq(1).html(price);
cells.eq(2).html(lastUpdated);
}
}

The above code is simple, as the tick arrives, it checks to see whether the table already has a row for that symbol, if so it updates the data otherwise it adds a new row for that symbol.


Thats all for this blog, if you want to check out the full source code, I encourage you to visit the Github project page.

Happy coding!

14 comments:

  1. I am continually amazed by the amount of information available on this subject. What you presented was well researched and well worded in order to get your stand on this across to all your readers. stock tips

    ReplyDelete
  2. Insurance is actually synonymous to numerous people discussing risks associated with losses expected from the supposed incident. Here, the expense of the actual losses is going to be borne by all of the insurers. www.insuranceadvice.us

    You can see all creates and shapes and sizes of fashion blogs for the internet is jam packed with them. It can converse about the luxury of wearing slim jeans across boyfriend shorts or ways pink takes the position of schokohäutige plus lots of the extras. Simply because go via the internet, you becomes your fill for the latest popular trends with fashion blogs. www.servicesdealer.us

    Most likely you view the trend in this article... Commercial House loan Financing can be employed in pretty much any marketplace for virtually any commercial property or home. Speak with all your Business Finance Broker while you are ready to invest in a Commercial Real estate investment opportunity. www.businessterms.us

    Travel's importance is actually underestimated by lots of people. Travel isn't just fun, enjoyable and pleasant. With the current life styles and function conditions, travel is becoming more than a choice. It is a lot more than just having a good time. www.cheaptraveldeals.us

    Health fitness suggestions also advise that vices needs to be stopped. Smoking predisposes anyone to vascular conditions for instance arteriosclerosis and also heart conditions. Alcohol consumption will not need to be eradicated but needs to be limited to be able to 30 jiggers per day only. Alcohol nonetheless has health improvements such since vasodilation. These are just some of what Health fitness suggestions recommend www.idealhealthfitness.us

    ReplyDelete
  3. Read you be conscious of the trend at this point... Commercial Bank loan Financing can be utilised in basically any community for any sort of commercial real estate. Speak in your Business Finance Broker while you're ready to buy a Commercial Properties opportunity. www.financebenefits.us

    You'll find all varieties and styles of fashion blogs because the internet is packed with them. It can speak about the main advantage of wearing slim jeans above boyfriend denims or just how pink takes the spot of african american plus every one of the extras. When you go on the web, you are certain to get your fill with the latest in fashion trends by means of fashion blogs. www.currentfashiontrend.com

    Real estate traders live as well as die through their capability to add worth. With absolutely no added worth, there tend to be no earnings. This holds true with any kind of business, but why is real estate this type of great business along with a great expense, is the amount of ways you can include value and profit from big earnings. www.commercialsproperty.us

    Are you thinking concerning remodeling the home? Take into account that you can frequently achieve the goal with out a giant expenditure. Small advancements introduced in virtually every room, including the surface of your home can make every one of the difference. www.houseInnovations.us

    The truth is that We can sit these today and even write what you deserve to be hunting for in business trends and be able to a 365 days from at present, write the exact same sort in article through different ideas to keep abreast of as business and even society evolve. www.theservicesexperience.com

    ReplyDelete
  4. Health fitness guidelines also advice that vices must be stopped. Smoking predisposes you to definitely vascular conditions including arteriosclerosis along with heart ailments. Alcohol consumption don't need to be taken away but must be limited for you to 30 jiggers every day only. Alcohol even now has benefits such while vasodilation. These are are just some of what Health fitness guidelines recommend www.healthcarecentre.us

    Are you currently thinking regarding remodeling your own home? Remember that you could achieve your own goal with no giant cost. Small enhancements introduced in nearly every room, including the outside of the home can make all of the difference. www.selecthomeadvisor.us

    Health fitness points also propose that vices need to be stopped. Smoking predisposes that you vascular conditions like arteriosclerosis in addition to heart disorders. Alcohol consumption does not need to be taken out but need to be limited to help 30 jiggers daily only. Alcohol however has health advantages such seeing that vasodilation. These are just some of what Health fitness points recommend www.healthcareaffect.us

    Just about everyone has heard the particular argument regarding spending a lot more now about quality to save lots of money afterwards. But think about the influence your purchase has on the planet, shouldn't shopping ethically engage in the debate too? www.eventsshopping.us

    There are actually all documents and forms and sizes of fashion blogs being the internet is heaped with them. It can go over the main advantage of wearing thin jeans finished boyfriend a pair of jeans or the simplest way pink takes site of charcoal plus the whole set of extras. Whenever you go over the internet, you could get your fill of this latest in fashion trends with the aid of fashion blogs. www.serviceadvisories.com

    Health fitness recommendations also suggest vices really should be stopped. Smoking predisposes want you to vascular conditions just like arteriosclerosis plus heart health conditions. Alcohol consumption needn't be wiped out but really should be limited so that you can 30 jiggers on a daily basis only. Alcohol continue to has rewards such when vasodilation. These are are just some of what Health fitness recommendations recommend www.healthifitness.us

    ReplyDelete
  5. You can get all versions and sizes and shapes of fashion blogs given that the internet is rife with them. It can consider the benefit of wearing skinny jeans throughout boyfriend tight pants or skirts or the correct way pink takes spot of black colored plus the extras. Whilst you go web based, you get your fill belonging to the latest popular trends using fashion blogs. www.globenewscenter.us

    You will discover all types and designs of fashion blogs since the internet is filled with them. It can discuss the benefit of wearing thin jeans more than boyfriend denim jeans or exactly how pink takes the area of dark plus all of the extras. While you go on the internet, you can get your fill from the latest popular trends by way of fashion blogs. www.fashionlabel.us

    One can find all methods and figures of fashion blogs when the internet is complete with them. It can focus on the advantage of wearing slender jeans about boyfriend pants or the way in which pink takes the location of ebony plus most of the extras. As you may go on line, you will receive your fill within the latest in fashion trends by fashion blogs. www.theworldnews.us

    I know that you read the trend these... Commercial Loan Financing should be considered in just about any trade for some kind of commercial premises. Speak with each of your Business Finance Broker if you end up ready to get a Commercial The property market opportunity. www.mybusinessmanager.us

    The laws associated with nature are simply as these people treat each and every specie (and not just man) along with equality. Inside a jungle, each and every specie will get its because of share associated with food, air as well as water that enable these phones live the dignified life without having to be dependent on every other creation. Character makes absolutely no distinction in between one specie, and also the other because all species would be the children from the same Lord. www.equallaw.us

    Health fitness hints also counsel that vices has to be stopped. Smoking predisposes to vascular conditions which include arteriosclerosis together with heart medical conditions. Alcohol consumption should not be taken off but has to be limited that will 30 jiggers each and every day only. Alcohol also has health and fitness benefits such mainly because vasodilation. These are just some of what Health fitness hints recommend www.healthandfoodideas.com

    ReplyDelete
  6. Health fitness tips and hints also suggest that vices could be stopped. Smoking predisposes people to vascular conditions along the lines of arteriosclerosis not to mention heart sicknesses. Alcohol consumption does not have to be got rid of but could be limited towards 30 jiggers a full day only. Alcohol even so has health rewards such for the reason that vasodilation. These are just some of what Health fitness tips and hints recommend www.healthfitnesstogether.com

    Seen you are aware of the trend in this case... Commercial Home owner loan Financing are available in very nearly any market place for any variety of commercial building. Speak utilizing your Business Finance Broker remember when you are ready to invest in a Commercial Realty opportunity. www.bestfinanceideas.com

    More than likely you understand the trend below... Commercial Home finance loan Financing works extremely well in nearly any sector for just about any commercial residence. Speak using your Business Finance Broker when you find yourself ready to get a Commercial Real estate property opportunity. www.businessplanning.us

    You will find all forms and shapes of fashion blogs as the internet is full of them. It can talk about the advantage of wearing skinny jeans over boyfriend jeans or how pink takes the place of black plus all the extras. As you go online, you will get your fill of the latest in fashion trends via fashion blogs. www.latestfashionz.us

    ReplyDelete
  7. Just come across WeBuyCheaper.com brings me a great deal of fun with home and bedroom ideas.

    ReplyDelete
  8. I am incapable of reading articles online very often, but I’m happy I did today. It is very well written, and your points are well-expressed. I request you warmly, please, don’t ever stop writing. MMA

    ReplyDelete
  9. Hire Angular JS Developers from well-famous Software, web, and app development companies, and save your hiring process based on different hiring models. Agnito Technologies is a leading software, web , and mobile app development company that offers to hire dedicated angular developers remotely for full-time, part-time, and an hourly basis as per your project requirements. If you are looking to get customized web apps to improve your web design architecture by using Angular js technologies then choose our expert team of Angularjs developers at a very low price.

    Hire Angular App Developers

    ReplyDelete