R/price.R

#' Gets the current XLM price.
#' @description Make a call to the Binance API and get the current XLM market price.
#' @param currency character - current pairings are USD, ETH, BTC and BNB. USD is worked out indirectly via BTC with two API calls.
#' @param live boolean - if true, a while loop will continuously get the latest price and print it to the screen.
#' @return numeric
#' @export
#' @note Details of API can be found here: https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md
#' @examples
#' price("USD")

price <- function(currency = "USD", live = FALSE) {
  currency = toupper(currency)

  if (!(currency %in% c("BTC", "ETH", "BNB", "USD"))){
    stop(sprintf("Invalid currency code: %s. Must be in: USD, BTC, BNB or ETH.", currency))
  }

  request = function(currency){
    if (currency == "USD") {
      p_xlm = content(GET(url = "https://api.binance.com/api/v1/ticker/price?symbol=XLMBTC"))
      p_btc = content(GET(url = "https://api.binance.com/api/v1/ticker/price?symbol=BTCUSDT"))
      return(c(USD = as.numeric(p_xlm$price) * as.numeric(p_btc$price)))
    } else {
      url = sprintf("https://api.binance.com/api/v1/ticker/price?symbol=XLM%s",
                    currency)
      p_xlm = as.numeric(content(GET(url = url))$price)
      names(p_xlm) = currency
      return(p_xlm)
    }
  }

  if(live){
    while(1){
      p = request(currency)
      cat("\r", sprintf("Price in XLM/%s: %s", names(p)[1], p))
      Sys.sleep(1)
      flush.console()
    }
  } else {
    return(request(currency))
  }

}
froocpu/stellaR documentation built on May 17, 2019, 7:05 p.m.