Now Playing Tracks

Stock Ticker in Node.js

Trying out stock ticker in Node.js. Suggestions are welcome :)

var fs = require('fs')
    , http = require('http')
    , socketio = require('socket.io')
    , connect = require('connect');

console.log("===Stock Ticker Application===")
 
var server = connect.createServer(
                connect.static(__dirname)
             ).listen(8080, function() {
                console.log('Listening at: http://localhost:8080');
             });

var io = socketio.listen(server);
 
io.sockets.on('connection', function (socket) {
    socket.on('message', function (ticker) {
        console.log('Message Received: ', ticker);
        setInterval(getStockQuote, 5000, ticker, socket);
    });
});

function getStockQuote(ticker, socket) {
    var options = {
        host: 'finance.google.com',
        port: 80,
        path: '/finance/info?client=ig&q=' + ticker,
        headers: {
            Host: "www.google.com"
        }
    };

    http.get(options, function(res) {
      var data = '';
      res.on('data', function (chunk) {
            data += chunk;
      });
      res.on('end',function(){
        var obj = JSON.parse(data.substring(3));
        var lastPrice =  { "ticker" : ticker , "last" : obj[0].l };
        //console.log(lastPrice)
        socket.emit('message', lastPrice);
      })
    }).on('error', function(e) {
      console.log("Got error: " + e.message);
    });
  }

Stock Ticker in Scala

I started to learn Scala last weekend and this is my first attempt write some code. I thought writing a stock ticker would be a good hello world application.

package com.scala.ticker
import java.net.URL
import scala.io.Source
import scala.xml.XML
import java.util.Timer
import java.util.TimerTask

object StockTicker {

  def main(args: Array[String]): Unit = {
    println("===Stock Ticker Application===")
    StockQuoteProcessor.start
    var tickers = readLine("prompt> ")
    while (true) {
    	println("====Fetching quotes with actors====")
    	tickers.split(",").foreach(s => StockQuoteProcessor ! s)
    	Thread sleep 5000
    }
  }
}

Scala actor to process stock tickers

package com.scala.ticker

import scala.actors.Actor._
import java.net.URL
import scala.xml.XML
import scala.actors.Actor
import java.util.Timer
import java.util.TimerTask

object StockQuoteProcessor extends Actor {
  def act() {
    loop {
      react {
        case ticker: String => getStockQuote(ticker)
      }
    }
  }

  def getStockQuote(ticker: String): Unit = {
    val url = new URL("http://www.google.com/ig/api?stock=" + ticker)
    val body = url.openStream()
    val xml = XML.load(body)
    val threadId = Thread.currentThread().getId
    val threadName = Thread.currentThread().getName()
    for (node  None
        case Some(lastPrice) => println("Thread [" + threadId + "-" + threadName + "] " +ticker + " = " + lastPrice)
      }
    }
  }
}
To Tumblr, Love Pixel Union