Created
March 25, 2009 03:52
-
-
Save weihsiu/84548 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CmdUtils.CreateCommand({ | |
name: "tw-stock", | |
author: { name: "Walter Chang", email: "[email protected]" }, | |
license: "Creative Commons 3.0 (by nc)", | |
description: "Quote a stock symbol from Taiwan Stock Exchange", | |
takes: {"stock symbol": noun_arb_text}, | |
preview: function(pblock, what) { | |
var msg = 'Gets stock quote for "${stockSymbol}"'; | |
var subs = { stockSymbol: what.text }; | |
pblock.innerHTML = CmdUtils.renderTemplate(msg, subs); | |
}, | |
execute: function(what) { | |
this._queryQuote(what.text); | |
}, | |
_queryQuote: function(stockSymbol) { | |
function plus(n) { return n > 0 ? "+" : ""; } | |
jQuery.get("http://tw.stock.yahoo.com/q/q", { s: stockSymbol }, function(content) { | |
var regexps = [new RegExp('\s*<td align="center" bgcolor="#FFFfff" nowrap><b>(.+)</b></td>\s*'), | |
new RegExp('\s*<td align="center" bgcolor="#FFFfff" nowrap>([^:]+)</td>\s*')]; | |
var items = []; | |
var lines = content.split("\n"); | |
for (var i in lines) { | |
for (var j in regexps) { | |
var matches = regexps[j].exec(lines[i]); | |
if (matches != null) { | |
items.push(matches[1]); | |
break; | |
} | |
} | |
} | |
if (items.length == 0) | |
displayMessage("Invalid stock symbol: " + stockSymbol); | |
else { | |
var msg = "${stockSymbol}: ${quote} ${diff} ${percentage}%" | |
var quote = parseFloat(items[0]); | |
var oldQuote = parseFloat(items[4]); | |
var diff = quote - oldQuote; | |
var percentage = diff / oldQuote * 100; | |
var subs = { stockSymbol: stockSymbol, quote: quote.toFixed(2), diff: plus(diff) + diff.toFixed(2), percentage: plus(percentage) + percentage.toFixed(2) }; | |
displayMessage(CmdUtils.renderTemplate(msg, subs)); | |
} | |
}); | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment