# R/websockets example
if(any(is.na(packageDescription('caTools'))))
stop("This demo requires the caTools package.\nRun install.packages('caTools') to install it.\n\n")
if(any(is.na(packageDescription('PerformanceAnalytics'))))
stop("This demo requires the PerformanceAnalytics package.\nRun install.packages('PerformanceAnalytics') to install it.\n\n")
library('websockets')
library('caTools')
library('PerformanceAnalytics')
require('RJSONIO')
data(managers)
# ------------------------------------------------------------------
# Here is the web page that we use for this example (it's saved to a
# temporary file):
webpage = function()
'
R/Websockets
|
Connection not initialized
|
'
id = 1 # id tracks each connected websocket client.
p = tempfile()
cat(webpage(),file=p)
w = createContext(webpage=p)
oldopt = options(warn=-1, demo.ask=FALSE)
types=c("PerformanceSummary","BoxPlot","RiskReturnScatter","RollingPerformance")
trailing36.rows = (nrow(managers)-36):nrow(managers)
# Set receive and broadcast callbacks
f = function(DATA,WS,COOKIE)
{
x = paste(rawToChar(DATA))
x = withCallingHandlers(strsplit(x,",")[[1]],error=function(e) character())
tryCatch(
if(nchar(x)>0) {
print(x)
cat("Client ID ",getCookie(COOKIE)," sent us some data!\n")
f = tempfile()
jpeg(file=f, width=850,height=500, quality=100)
devAskNewPage(ask=FALSE)
chartType = x[1]
x = x[-1]
if(chartType == types[1])
charts.PerformanceSummary(managers[, x], colorset = rich6equal, lwd = 2, ylog = TRUE)
else if(chartType == types[2])
chart.Boxplot(managers[trailing36.rows, x], main = "Trailing 36-Month Returns")
else if(chartType == types[3])
chart.RiskReturnScatter(managers[trailing36.rows, 1:8], Rf = 0.03/12, main = "Trailing 36-Month Performance")
else if(chartType == types[4])
charts.RollingPerformance(managers[, x], Rf = 0.03/12, colorset = c("red", "blue", "cyan", "yellow", "black", "orange", "green"), lwd = 2)
dev.off()
p <- base64encode(readBin(f,what="raw",n=1e6))
p <- paste("data:image/jpg;base64,\n",p,sep="")
websocket_write(paste(p),WS)
file.remove(f)
}, error=function(e) print(e));
}
setCallback("receive",f, w)
h = function(DATA, WS, COOKIE)
{
cat("Client ID ",getCookie(COOKIE), " closed its connection.\n")
}
setCallback("closed",h, w)
# Set up an established (initialization) callback
g = function(DATA, WS, COOKIE)
{
setCookie(COOKIE, paste(id))
websocket_write(toJSON(list(portfolios=colnames(managers),types=types)),WS);
id <<- id + 1
}
setCallback("established",g, w)
cat("\nThe web service will run until +C is pressed.\n")
cat("Open your local web browser to http://localhost:7681\n")
while(TRUE) {
service(w)
Sys.sleep(0.05)
}
rm(w)
gc()
file.remove(p)
options(oldopt)