Skip to content

Instantly share code, notes, and snippets.

@praetoriansentry
Last active December 16, 2015 03:09
Show Gist options
  • Save praetoriansentry/5368358 to your computer and use it in GitHub Desktop.
Save praetoriansentry/5368358 to your computer and use it in GitHub Desktop.
Minor variation of the BTC script so that the amount of time can be controlled.
library("rjson")
library("quantmod")
##### Configuration #####
startTime <- as.integer(as.POSIXct(strptime("2013-04-09 00:00:00", "%Y-%m-%d %H:%M:%S")))
endTime <- as.integer(Sys.time())
bucketSize <- 60*15 # Fifteen minutes
##### Implementation #####
json_file <- "https://data.mtgox.com/api/2/BTCUSD/money/trades/fetch?since="
trades <- list()
while (startTime < endTime - bucketSize) {
print(strftime(as.POSIXct(startTime, origin="1970-01-01"), format="%Y-%m-%d %H:%M:%S"))
json_data <- fromJSON(paste(readLines(paste(json_file,startTime,"000000", sep="")), collapse=""))
mtgox <- json_data$data
newStart <- max(do.call(rbind.data.frame, mtgox)$date)
if (newStart == startTime) {
break
}
startTime <- newStart
trades <- c(trades, mtgox)
Sys.sleep(5)
}
trades <- do.call(rbind.data.frame, trades)
trades <- trades[order(trades$date),]
trades$bucket <- floor(trades$date / bucketSize)
buckets <- unique(trades$bucket)
BTC.Dates <- lapply(buckets, function(x){
first(as.integer(as.character(trades[trades$bucket == x,]$date)))
})
BTC.Open <- lapply(buckets, function(x){
first(as.double(as.character(trades[trades$bucket == x,]$price)))
})
BTC.High <- lapply(buckets, function(x){
max(as.double(as.character(trades[trades$bucket == x,]$price)))
})
BTC.Low <- lapply(buckets, function(x){
min(as.double(as.character(trades[trades$bucket == x,]$price)))
})
BTC.Close <- lapply(buckets, function(x){
last(as.double(as.character(trades[trades$bucket == x,]$price)))
})
BTC.Volume <- lapply(buckets, function(x){
sum(as.double(as.character(trades[trades$bucket == x,]$amount)))
})
BTC <- data.frame(
"Open" = as.double(BTC.Open),
"High" = as.double(BTC.High),
"Low" = as.double(BTC.Low),
"Close" = as.double(BTC.Close),
"Volume" = as.double(BTC.Volume)
)
BTC <- as.xts(BTC, order.by=as.POSIXlt(unlist(BTC.Dates), origin="1970-01-01", tz="GMT"))
chartSeries(BTC)
addMACD()
addBBands()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment