Stock's Symbol-Based Quote and Ticker With Yahoo FEED

By Praveen Gupta, April 24, 2009

StockQuote is a simple JavaFX application that provides the current stock data based on the Yahoo Symbols. User needs to use the stock symbols provided by Yahoo. The results are provided in CSV files and are parsed using simple Java string API. The results are displayed in a simple GUI, which shows the details of last trade price, day Range, volume, last closing price and so on. The stock price are shwon in the country's specific currency. For example if you enter JAVA ( stock symbol for SUN Microsystem Inc.); stock price will be in USD (American Currency), as this stock symbol is listed in NASDAQ. And if you enter stock symbol listed in Indian Stock Exchange, stock price will be in INR (Indian Currency)

Understanding the Code

getQuote function is heart and soul of the application. After validating the user input, http request is sent to yahoo. Another validation is done on response data as well.

Source Code
    
function getQuote(symbol:String): Void {
	var data:String;
	println("Loading Stock quote here...:{symbol}");
	// Submit HttpRequest
	var request: HttpRequest = HttpRequest {
		location: "http://download.finance.yahoo.com/d/quotes.csv?s={symbol}...";
		//method: HttpRequest.GET
		onException: function(exception: Exception) {
			exception.printStackTrace();
			httpRequestError = true; 
		}
		onResponseCode: function(responseCode:Integer) {
			if (responseCode != 200)
			println("failed, response: {responseCode} {request.responseMessage}");
		}

		onInput: function(input: java.io.InputStream) {
			try {
				httpRequestError = false;
				var parser = new DataParser();
				data= parser.getData(input);                    
			} finally {
				input.close();
			}
		}
		onDone: function() {
			if(not httpRequestError) {
				QuoteData = parseQuoteData(data);
				if(ShowFrameData) {
					println("ShowFrameData {QuoteData}");
					setFrameData(QuoteData);
				}
				else {
					println("ShowTickerData {QuoteData}");
					showTicker(QuoteData,symbol);
				}
			}
		}
	}
	request.enqueue();
}    

parseQuoteData function parse the stocke quote and store them into a result data array. This function is using simple Java String APIs to do the parsing.

Source Code
    
public function parseQuoteData(data:String): String[]{
    println("starting parseQuoteData {data}");
    var result:String[];
    var StartIndex = 0;
    var fromIndex=0;
    // Parse all data recieved with response. First split the data with comma
    //Make an array and remove double quotes from all the array elements.
	for(i in [0..15]) {
        fromIndex = data.indexOf(",", StartIndex);
        if ((i == 15)) {
            if(fromIndex == - 1){
                insert data.substring(StartIndex,data.length()) into result;
            }
            else {
                insert data.substring(StartIndex,fromIndex) into result;
            }
        }
        else {
            insert data.substring(StartIndex,fromIndex) into result;
        }
        StartIndex = fromIndex + 1;
        //remove double quotes from all the array elements.
        if("{result[i]}".indexOf("\"") == 0)
            result[i] = "{result[i]}".substring(1);
        var lastIndexOfDComma = "{result[i]}".indexOf("\"",1);
        if(lastIndexOfDComma > 0)
            result[i] = "{result[i]}".substring(0,lastIndexOfDComma);
    }
    return result;
    }
} 

Results are shown to the user using the javafx.stage and javafx.scene classes. The query is processed and latest stock informations is obtained. The stock details are provided in the application frame. The application has two part; one is for the to show the full stock information in main frame and this can be called frame area. Other part is to show the stock ticker called ticker area. In user action, stock details are fetch when user provides the symbol in text box area and data is shwon in the frame area. Ticker shows the current stock quote for all the symbols user has searched . The ticker will start automatically and qoutes will be shown one by one in the ticker area.

The information is retrieved by performing an HTTP GET request using the JavaFX asynchronus HTTP API (javafx.io.http.HttpRequest). The document in the response is parsed by using the Java string API. User enters the symbol in the text box and request is sent to download.finance.yahoo.com; if symbol is a valid symbol then reponse data is parse and for a non vlaid symbol error message is displyed.

Constraints provided in the requests for Stock quote are:

  • Stock symhbol should be valid symbol and it should match with the symbol from obtained from finance.yahoo.com
  • Stock price are shown in the local countery currency format. US Dollor for NASDAQ and Indian Rupee for BSE (Bombay Stock Exchnage) etc.
  • It shows stock price for all the valid symbols accross all counteries as reconogized by finance.yahoo.com

The response contains a Comma Seperated Values File (CSV). The response data has more information but applicatin only shows thses informations.

  • Company Name
  • Last Trade price
  • Change from previous day in precentage as well
  • Today's Range
  • Previous Day Closing Price
  • Volume
  • Last Trading Date and Time

The response input stream is being read into byte array and converted into data string. The data string has comma separted values.These values are stored into an array and above mentioned data is shown. If stock price has increase from previous day close, change values will be shown in GREEN color. If stock price has come down, change values will be shown in the RED color. Otherwise stock price will be shown in balck color. After stock quote is displyed, will be added into the ticker area. If you are using proxy-server for connecting to internet, please follow setup as specified in "Java Networking and Proxies".

References