CFDs are complex instruments and come with a high risk of losing money rapidly due to leverage. 66 % of retail investor accounts lose money when trading CFDs with this provider. You should consider whether you understand how CFDs work and whether you can afford to take the high risk of losing your money.

Easy saving quote stream into csv with R

Hi all! I was looking for something like this a few days ago.

Run R terminal, setwd("~/") and source(“thiscode.R”)

# Save darwins quotes into .csv file

###############################################

token <- "***" # Your token here
datadir <- "~/" # Where to save the data
darwins <- c("DWC.4.20","DWF.4.19") # Darwins full names
names(darwins) <- c("DWC","DWF") # Single names

###############################################

# Load required packages
required_packages <- c("tcltk2","data.table","RCurl")

for(pack in required_packages){
  ifelse(pack %in% rownames(installed.packages()) == FALSE,
         install.packages(pack),
         require(pack,character.only = TRUE))
}


# Set stream & save function
getDWQuotes <- function(darwins,token,datadir){
  
  str <- paste("curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'Authorization: Bearer ",
               token,"' -d '{\"productNames\":[\"",paste(darwins,sep="",collapse = "\",\""),"\"]}' 'https://api.darwinex.com/quotes/1.0/quotes'",sep="")
  a <- system(str,intern=TRUE)
  a <- gsub("\"", "", a, fixed=TRUE)
  a <- gsub("{","", a, fixed = TRUE)
  a <- gsub("}", "", a, fixed = TRUE)
  
  for(darwin in darwins){
    b <- a[grepl(darwin,a)]
    b <- gsub(paste("productName:", darwin, ",", sep=""), "", b)
    b <- gsub("quote:","",b)
    b <- gsub("timestamp:", "", b)
    b <- unlist(strsplit(b, ","))
    b <- matrix(as.numeric(b), ncol=2, byrow = TRUE)
    b <- data.frame(cbind(b[,2], b[,1]))
    b[,1] <- as.POSIXct(b[,1]/1000, origin = "1970-01-01", tz = "UTC")
    write.table(b,
                paste(datadir,names(darwins[darwins==darwin]), "_", format(Sys.Date(), "%Y"), ".csv",sep=""),
                append = TRUE, row.names = FALSE, col.names = FALSE, sep = ",")
  }
}

# Schedule it
tclTaskSchedule(wait=1, getDWQuotes(darwins,token,datadir), id="getDWQuotes", redo=TRUE)
3 Likes

This code does not look nice, but this way of “reading” from json is working well instead failed connections.

If any one else is seriously considering a R implementation of the DARWINEX APIs any contribution and suggestion will be welcome. If not, and you are reading, maybe any reason for not doing it in R will be appreciated too.

I am struggling with many many problems, since i am not professional developer, never used javascript, curl requests… the only convexity i see for the moment is an exponential and never ending learning curve.

I have a lot of questions, and responses take long time and effort to arrive:
Is good idea use system(“curl …”)?
I need lot of hours reading documentation to reasonably implement curl package, does it worth?
It is working fine for the moment, except for streaming, and beside fromJSON all API functions I tried worked fine.

Some examples:

# Get a list of all active darwins
#
getDWList <- function(token){
  tmp <- system(paste(
    "curl -k -X GET \"https://api.darwinex.com/darwininfo/1.3/products?status=ACTIVE&per_page=10000\" -H \"accept: application/json\" -H \"Authorization: Bearer ",
    token,"\"",sep = ""),
    intern=TRUE)
  rbindlist(fromJSON(tmp)$content)[,c(1,2)]
}
#
darwins <- getDWList(token)
#
# Note that some symbols like "ATR" could match sourced functions
#
discriminated.darwins <- c("ATR","EMA")
darwins <- darwins[!(darwins$shortName %in% discriminated.darwins),]
#
# Download quotes and save/update them in separate xts objects
#
getDWQuotes <- function(token,lookback){
  
  for(darwin in darwins$productName[]){

    tmp <- fromJSON(system(paste("curl -k -X GET \"https://api.darwinex.com/darwininfo/1.1/products/",
                                 darwin,"/history/quotes?start=",as.integer(Sys.time()-(60*60*lookback))*1000,
                                 "\" -H \"accept: application/json\" -H \"Authorization: Bearer ",token,"\"",
                                 sep=""),intern = TRUE))
    tmp <- xts(tmp[,2],order.by = as.POSIXct(tmp[,1]/1000,origin = "1970-01-01"))
    if(!exists(substr(darwin,1,3))){
      assign(substr(darwin,1,3),tmp,envir=.GlobalEnv)
    }else{
      old <- get(substr(darwin,1,3))
      new <- rbind(old,tmp)
      new <- new[!duplicated(index(new))]
      assign(substr(darwin,1,3),new,envir=.GlobalEnv)
    }
    # Do not excess 50 requests/minute
    pause(1.1)
  }
}
#
# Buy something
#
enterLong <- function(token,id,amount,darwin){
  str <- paste("curl -k -X POST \"https://api.darwinex.com/trading/1.0/investoraccounts/",id,"/orders/buy\" -H \"accept: application/json\" -H \"Content-Type: application/json\" -H \"Authorization: Bearer ",token,"\" -d \"{ \\\"amount\\\": ",amount,", \\\"productName\\\": \\\"",darwin,"\\\"}\"",sep="")
  system(str)
}
#
# Exit all open positions
#
stopOut <- function(token,id){
  system(paste("curl -k -X POST \"https://api.darwinex.com/trading/1.0/investoraccounts/",id,"/stopout\" -H \"accept: application/json\" -H \"Authorization: Bearer ",token,"\"",sep=""))
}

Would love a full trading environment in R

Trade safe!

1 Like

Hi @naturalcapital ,

I’m afraid we cannot give support for every existing programming language, so we could answer in relation to our API offering but not about issues with specific clients or how to develop against the existing API.

Nevertheless, as R is an important language mainly used for stats / maths / … I was wondering if I were able to use it against our API too. (even-though I haven’t ever develop in R)

And here I have an example of usage against our API:

# install httr / rjson if not available
install.packages('httr') 
install.packages('rjson')

library(httr)
library(rjson)  

query <- "https://api.darwinex.com/darwininfo/products?status=ALL&page=0&per_page=10"
getdata <- GET(url=query, add_headers(Authorization="Bearer <api_token>", accept="application/json"))

fromJSON(content(getdata,type="text"))
fromJSON(content(getdata,type="text"))$content

# loop through the content
for (product in fromJSON(content(getdata,type="text"))$content) {
 print(paste(product$productName))
}

Our API store gives examples of usage of the APIs with curl but these are just examples. Every programming language might have their own libraries or methods to connect with an API. In the case of R, there are libraries like the “httr” used in the example, but there are even more libraries.

Furthermore, I have noticed that the tool swagger-codegen in the version 2.. had a client code generator for R:
https://swagger.io/tools/swagger-codegen/
Using the swagger-codegen against our swagger spec, which can be found as a link in each one of the API Consoles of the store, an R-api-client could be built. (although it didn’t work to me)

swagger-codegen -l r -i https://api.darwinex.com/store/api-docs/admin/DarwinInfoAPI/1.3

I hope it helps a bit :wink:

2 Likes

Thank you very much! @jesusbc

2 Likes