Skip to content

Instantly share code, notes, and snippets.

@paduel
Created July 6, 2019 16:24
Show Gist options
  • Save paduel/3a163cd363b06f418663a9723340eb1d to your computer and use it in GitHub Desktop.
Save paduel/3a163cd363b06f418663a9723340eb1d to your computer and use it in GitHub Desktop.
Import Metatrader .hst files to R dataframe
read_hst <- function(filename){
library(anytime)
hst_file <- file(filename, "rb")
version <- readBin(hst_file, integer(), 1, size = 4, endian="little")
head <- readBin(hst_file, character(), 22, endian="little")
symbol <- head[22]
print(paste(symbol, "hst to dataframe"))
datetime <- c()
open <- c()
high <- c()
low <- c()
close <- c()
volume <- c()
spread <- c()
real_volume = c()
seek(hst_file, 148, origin = 'start')
if (version==401){
for (i in 1:((file.info(filename)$size - 148) / 60)){
datetime[i] <- readBin(hst_file, integer(), size=8)
open[i] <- readBin(hst_file, double(), 1, size=8, endian="little")
high[i] <- readBin(hst_file, double(), 1, size=8, endian="little")
low[i] <- readBin(hst_file, double(), 1, size=8, endian="little")
close[i] <- readBin(hst_file, double(), 1, size=8, endian="little")
volume[i] <- readBin(hst_file, integer(), 1, size=8, endian="little")
spread[i] <- readBin(hst_file, double(), size=4)
real_volume[i] <- readBin(hst_file, integer(), 1, size=8, endian="little")
}
datetime <- anytime(datetime)
data <- data.frame(datetime, open, high, low, close, volume, spread, real_volume)
} else if (version==400){
for (i in 1:((file.info(filename)$size - 148) / 48)){
datetime[i] <- readBin(hst_file, integer(), size=8)
open[i] <- readBin(hst_file, double(), 1, size=8, endian="little")
high[i] <- readBin(hst_file, double(), 1, size=8, endian="little")
low[i] <- readBin(hst_file, double(), 1, size=8, endian="little")
close[i] <- readBin(hst_file, double(), 1, size=8, endian="little")
volume[i] <- readBin(hst_file, double(), 1, size=8, endian="little")
}
datetime <- anytime(datetime)
data <- data.frame(datetime, open, high, low, close, volume)
}
return(data)
}
@paduel
Copy link
Author

paduel commented Jul 6, 2019

To use it, pass to the function the name (path) of the .hst file, for example:

data<-read_hst("NZDUSD1440.hst")

and the df variable will receive a R data frame.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment