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

By Praveen Gupta, April 24, 2009

StockQuote is a simple JavaFX application that provides current stock data using Yahoo Symbols. User needs to use the stock symbols provided by Yahoo. Results are provided in CSV files and are parsed using simple Java string API. The results are displayed in a simple GUI, which shows details of last trade price, day Range, volume, last closing price and so on. Stock price is displayed using country specific currency. For example if you enter ORCL ( stock symbol for ORACLE Corporation ); stock price will be displayed in USD (American currency), as this stock symbol is listed on NASDAQ. And if you enter stock symbol listed on 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 parses the stock quote and stores 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 parts; 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 fetched when user provides the symbol in text box area and data is shown in the frame area. Ticker shows the current stock quote for all the symbols user has searched . The ticker will start automatically and quotes will be shown one by one in the ticker area.

The information is retrieved by performing an HTTP GET request using the JavaFX asynchronous 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 response data is parsed and for a non valid symbol error message is displayed.

Constraints provided in the requests for Stock quote are:

  • Stock symbol should be valid symbol and it should match with the symbol from obtained from finance.yahoo.com
  • Stock price are shown in the local country currency format. US Dollar for NASDAQ and Indian Rupee for BSE (Bombay Stock Exchange) etc.
  • It shows stock price for all the valid symbols across all countries as recognized by finance.yahoo.com

The response contains a Comma Separated Values File (CSV). The response data has more information but application only shows these informations.

  • Company Name
  • Last Trade price
  • Change from previous day in percentage 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 separated 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 black color. After stock quote is displayed, 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