R/candles.R

Defines functions candles

Documented in candles

#' Get Candlestick Data
#'
#' Retrieves historical candlestick data for a given stock symbol
#' within the specified date range. The API token is retrieved from
#' an environment variable 'LIMEX_API_TOKEN'.
#'
#' @param symbol Stock symbol to fetch candlestick data for.
#' @param from Starting date for the candlestick data in 'YYYY-MM-DD' format.
#' @param to Ending date for the candlestick data in 'YYYY-MM-DD' format.
#' @param timeframe Timeframe, min - 1, hour - 2, day - 3, week - 3, month - 5
#' @return A data frame containing the candlestick data if the request was successful, NULL otherwise.
#' @import jsonlite
#' @import httr
#' @examples
#' \dontrun{
#'   candles_data <- candles(symbol = "BRX", from = "2023-07-31", to = "2023-08-24")
#' }
#' @export
candles <- function(symbol='AAPL', from = "2023-07-31", to = Sys.Date(),timeframe=3) {
  # Retrieve the API token from the environment variable
  token <- Sys.getenv('LIMEX_API_TOKEN')
  old <- options()
  on.exit(options(old))
  options(timeout=300)
  if (token == "") {
    stop("API token is not set. Use set_limex_token() to set it before making API calls.")
  }

  # Construct the URL with the provided parameters
  url <- sprintf('https://hub.limex.com/v1/candles?symbol=%s&from=%s&to=%s&token=%s&timeframe=%s',
                 symbol, from, to, token,timeframe)

  # Use tryCatch to handle errors
  data <- tryCatch({
    response <- fromJSON(url, simplifyMatrix = TRUE)
    data = data.table(response)
    if (timeframe >=3) data$ts = as.Date(data$ts)
    setkeyv(data,names(data)[1])
    return(data)
  }, error = function(e) {
    message("An error occurred: ", e$message)
    return(NULL)
  })

  return(data)
}

Try the limexhub package in your browser

Any scripts or data that you put into this service are public.

limexhub documentation built on June 22, 2024, 6:58 p.m.