Thursday, June 26, 2014

F# example: Getting live stock ticks through Google Finance API

NOTE: This article demonstrates how F# in conjunction with Reactive Extensions can be used to connect to live data streaming. The full project with example client can be found at This Github link.

Disclaimer

I do not  take any responsibility of the code and any damages caused by it. Code which is provided AS IS is only for demonstration purposes and in no way encourages anyone to use Google Finance API for business. 

Introduction

It has been a week learning F# and I have finally converted my C# code that uses Google Finance API to F#

Here is what my code does. In simple words, it gives you back the IObservable<Tick> for one security (or symbol)

Here is the screenshot of how it looks like


Here is how you use it as a library in C#
 DataMachine machine = new DataMachine();  
 IObservable<Tick> appleTicker = machine.GetStockQuote("AAPL"); // Get Apple's stock prices  
 appleTicker.Subscribe(tick => {  
        // Everytime price changes, this piece of code will be called and an   
       // An object of Tick will be supplied as tick  
       // You can either add them to your Graph series to plot live chart  
       // Or save them to CSV  
       });  

Google Finance API

The simple finance API by Google is just a URL that takes symbol in 'q' GET parameter (or query string parameter). The following will give you the current price data for Yahoo in Json format.


How it works ?

It creates a thread using TaskFactory which queries Google Finance every 1 second, fetches the price and if there is a change in price produces the output into the Observable. Google Finance API gives back Json object. I am using Json.Net library by James-Newton King to parse that.

Here is the type definition of Tick
 type Tick() =   
     [<JsonProperty(PropertyName = "t")>]   
     member val Symbol = Unchecked.defaultof<string> with get, set  
     [<JsonProperty(PropertyName = "l")>]  
     member val Price = Unchecked.defaultof<float> with get, set  
     [<JsonProperty(PropertyName = "lt_dts")>]  
     member val LastUpdated = Unchecked.defaultof<DateTime> with 

Here is the code for DataMachine type
 type DataMachine() =   
   member this.GetLiveGoogleApiTicks(symbol : string) =  
     //google_api queries Google APi every second and produces the string output  
     let google_api (symbol : string) =  
       // When operation is cancelled by the caller, this variable will be modified  
       let cancelled = ref false  
       let operation(o : IObserver<string>) =  
         //Time to wait before fetching again through the API  
         let timeToSleep = TimeSpan.FromSeconds(1.0)  
         //Google Finance API , notice q is the query string parameter for symbol  
         let urlBuilder = new StringBuilder("""http://www.google.com/finance/info?q=""")  
         urlBuilder.Append symbol  
         let url = urlBuilder.ToString()  
         let client = new WebClient()  
         let cancelToken = Task.Factory.CancellationToken  
         client.BaseAddress = url  
         let task() =  
               try  
                 while not cancelToken.IsCancellationRequested && not !cancelled do  
                   let data = client.DownloadString url  
                   //Produce the item in observable  
                   o.OnNext data  
                   Thread.Sleep timeToSleep  
                   while client.IsBusy do  
                     Thread.Sleep 100  
               finally  
                   ignore  
         Task.Factory.StartNew task       
         let a = new Action(fun () -> (cancelled := true))  
         a |> Disposable.Create  
       Observable.Create(operation)  
     let strings = (google_api symbol)  
     // Eliminate unparseable characters for Json.Net library  
     let trimmed = strings.Select (fun (l:string) -> l.Substring(l.IndexOf("[") + 1, l.LastIndexOf("]") - 2 - l.IndexOf("[") + 1))  
     //Parse into object and return the IObservable<Tick>  
     trimmed.Select(fun (l:string) -> JsonConvert.DeserializeObject(l)).DistinctUntilChanged(fun (a:Tick) -> a.Price)
     

Remember to add Rx-Main and Json.Net from Nuget in your project and add appropriate 'open' declarations for namespaces.


Download the code


The fully functional project with sample client for this project can be found at This Github link.

Let me know your comments in the section below. If there is anything that I should have done differently, I would love to hear about that.

Happy coding!

20 comments:

  1. It feels awe-inspiring to read such informative and distinctive articles on your websites.
    North Creek Financial

    ReplyDelete
  2. I like your post. It is good to see you verbalize from the heart and clarity on this important subject can be easily observed... national savings

    ReplyDelete
  3. Hi! This is my first visit to your blog! We are a team of volunteers and new initiatives in the same niche. Blog gave us useful information to work. You have done an amazing job! cheaploansdirectory.com

    ReplyDelete

  4. Remember that paying little heed to how much pay you gain, the way to keeping up money related steadiness is through shrewd obligation the board and personal finance planning.Michael

    ReplyDelete
  5. Despite the fact that an ever increasing number of business sectors are getting to be soaked, you can even now exploit them because of the steady increment of the Internet advertise. make money online

    ReplyDelete
  6. This article is an appealing wealth of useful informative that is interesting and well-written. I commend your hard work on this and thank you for this information. I know it very well that if anyone visits your blog, then he/she will surely revisit it again. Instant payday loans

    ReplyDelete
  7. Glad to chat your blog, I seem to be forward to more reliable articles and I think we all wish to thank so many good articles, blog to share with us. كول كورة

    ReplyDelete
  8. It was wondering if I could use this write-up on my other website, I will link it back to your website though.Great Thanks. Arizona emergency cash

    ReplyDelete
  9. A delightful reading for anyone who loves reading blogs.
    mortgagecalculator.website

    ReplyDelete
  10. dengan memiliki rasa coklat permen soloco sangat cocok bisa menambah suasana romantis yang mendalam saat bercinta bersama pasangan. baca tautan . wanita membutuhkan durasi yang lama saat berhubungan badan, obat luar seperti hajar jahanam cair obat kuat original bisa mencegah terjadinya ejakulasi dini yang terlalu cepat jadi bisa menambah kepuasan dalam bercinta bersama pasangan. klik disini . satu lagi obat luar jenis cream yang sekarang ini banyak diburu seperti cream stud 007 obat kuat aman yang sekaligus dapat digunakan sebagai gel pelicin sebelum berhubungan intim agar mempermudah masuknya saat penetrasi. info selengkapnya . besar dan panjangnya ukuran alat kelamin pria bisa menambah kepuasan wanita secara maksimal dengan cara menggunakan terapi pro extender secara rutin akan mendapatkan hasil yang maksimal.

    ReplyDelete
  11. I am genuinely thankful to the holder of this web page who has shared this wonderful paragraph at at this place State of Origin 2020live streaming

    ReplyDelete
  12. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. slick cash loan

    ReplyDelete
  13. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. slick cash loan

    ReplyDelete
  14. Hi to everybody, here everyone is sharing such knowledge, so it’s fastidious to see this site, and I used to visit this blog daily imarketslive sign up

    ReplyDelete
  15. I like your post. It is good to see you verbalize from the heart and clarity on this important subject can be easily observed... XDCE

    ReplyDelete
  16. Awesome and interesting article. Great things you've always shared with us. Thanks. Just continue composing this kind of post. slickcashloan.com

    ReplyDelete
  17. It would appear to be outlandish for a bank not to give a credit, to a solid private venture. Most brokers feel that there are less organizations to loan to, however are anxious to begin loaning to trustworthy up-and-comers. wells fargo check routing number

    ReplyDelete
  18. When you use a genuine service, you will be able to provide instructions, share materials and choose the formatting style. Azizi Jawad

    ReplyDelete
  19. I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information. internal audit management software

    ReplyDelete