Git Product home page Git Product logo

serkor1 / cryptoquotes Goto Github PK

View Code? Open in Web Editor NEW
26.0 4.0 24.0 28.21 MB

cryptoQuotes is an R package for retrieving historical and real-time cryptocurrency market data from multiple exchanges. It offers an easy-to-use interface for accessing price quotes, trading volumes, and market data, making it valuable for analysts, developers, and crypto enthusiasts.

Home Page: https://serkor1.github.io/cryptoQuotes/

License: GNU General Public License v2.0

R 100.00%
cryptocurrencies cryptocurrency cryptocurrency-exchanges r binance binance-api kucoin kucoin-api kraken-api kraken-exchange-api

cryptoquotes's Introduction

cryptoQuotes: Open access to cryptocurrency market data cryptocurrency in R

CRAN status CRAN RStudio mirror downloads R-CMD-check codecov Lifecycle: stable GitHub last commit (branch)

ℹ️ About

The cryptoQuotes-package is a high-level API client for accessing public market data endpoints on major cryptocurrency exchanges. It supports open, high, low, close and volume (OHLC-V) data and a variety of sentiment indicators; the market data is high quality and can be retrieved in intervals ranging from seconds to months. All the market data is accessed and processed without relying on crawlers, or API keys, ensuring an open, and reliable, access for researchers, traders and students alike. There are currently 5 supported cryptocurrency exchanges,

Supported exchanges
binance bitmart bybit kraken kucoin

All data is returned as xts-objects which enables seamless interaction with with quantmod and TTR, for developing and evaluating trading strategies or general purpose cryptocurrency market analysis with a historical or temporal perspective.

ℹ️ Overview

The cryptoQuotes-package has two main features; retrieving cryptocurrency market data, and charting. The market data consists of OHLC-V data and sentiment indicators; including, but not limited to, cryptocurrency fear and greed index, long-short ratio and open interest. All market data is retrieved using the family of get_*-functions. To get a full overview of the package and functionality please see the documentation on pkgdown.

Note: Given the nature of crypotcurrency data and general legislative restrictions, some exchanges may not work in your geolocation.

Below is a quick overview of the package and basic usage examples on retrieving and charting Bitcoin (BTC) OHLC-V and long-short ratio in 30 minute intervals.

ℹ️ Cryptocurrency market data

OHLC-V

All supported exchanges and markets are listed in the table below, alongside the available range of intervals available from the respective exchanges,

Supported exchanges, markets and intervals.
Exchange Spot Futures Available Intervals Smallest Interval Biggest Interval
Binance 16 1 second(s) 1 month(s)
Bitmart 13 1 minute(s) 1 week(s)
Bybit 13 1 minute(s) 1 month(s)
Kraken 10 1 minute(s) 2 week(s)
Kucoin 13 1 minute(s) 1 week(s)
Example: Bitcoin OHLC-V

Get USDT denominated Bitcoin (BTC) on the spot market from Binance in 30m-intervals using the get_quote()-function,

## BTC OHLC prices
## from Binance spot market
## in 30 minute intervals
BTC <- cryptoQuotes::get_quote(
  ticker   = 'BTCUSDT',
  source   = 'binance',
  futures  = FALSE,
  interval = '30m',
  from     = Sys.Date() - 1 
)
Bitcoin (BTC) OHLC-V data
index open high low close volume
2024-05-31 18:00:00 67215.58 67352.41 66670 67000.01 2093.77494
2024-05-31 18:30:00 67000.01 67221.53 66876.8 67200.01 788.25693
2024-05-31 19:00:00 67200.01 67459.66 67160.3 67417.98 598.68095
2024-05-31 19:30:00 67417.98 67455.93 67287.97 67342.77 287.26257
2024-05-31 20:00:00 67342.77 67444.47 67288.2 67305.5 383.04002
2024-05-31 20:30:00 67305.5 67427.68 67170 67400 468.98276

Sentiment indicators

The sentiment indicators available in the cryptoQuotes-package can be divided in two; derived indicators and market indicators. The former is calculated based on, for example, the price actions such as the Moving Average Convergence Divergence (MACD) indicator. The latter are public indicators such as the long-short ratio or fear and greed index; these are retrieved using the family of get_*-functions, while the derived indicators can be created using, for example, TTR.

In this overview we are focusing on market indicators made public by the cryptocurrency exchanges. For a full overview of sentiment indicators please refer to the documentation on pkgdown. All supported market indicators by exchange are listed in the table below,

Available sentiment indicators by exchange
Endpoint Binance Bitmart Bybit Kraken Kucoin
Long-Short Ratio
Open Interest
Funding Rate
Example: Bitcoin Long-Short Ratio

Get the long-short ratio on Bitcoin (BTC) using the get_lsratio()-function,

## BTC OHLC prices
## from Binance spot market
## in 30 minute intervals
BTC_LS <- cryptoQuotes::get_lsratio(
  ticker   = 'BTCUSDT',
  source   = 'binance',
  interval = '30m',
  from     = Sys.Date() - 1 
)
Long-Short Ratio on Bitcoin (BTC)
index long short ls_ratio
2024-05-31 18:00:00 0.679 0.321 2.114
2024-05-31 18:30:00 0.687 0.313 2.199
2024-05-31 19:00:00 0.696 0.304 2.289
2024-05-31 19:30:00 0.699 0.301 2.323
2024-05-31 20:00:00 0.696 0.304 2.288
2024-05-31 20:30:00 0.696 0.304 2.293

ℹ️ Charting

Charting in the cryptoQuotes-package is built on plotly for interactivity. It supports light and dark themes, and accounts for color-deficiency via the options-argument in the chart()-function.

Charting with indicators

The OHLC-V data and the sentiment indicator can be charted using the chart()-function,

## Chart BTC
## using klines, SMA
## Bollinger Bands and
## long-short ratio
cryptoQuotes::chart(
  ticker = BTC,
  main   = cryptoQuotes::kline(),
  sub    = list(
    cryptoQuotes::lsr(ratio = BTC_LS),
    cryptoQuotes::volume()
  ),
  indicator = list(
    cryptoQuotes::sma(n = 7),
    cryptoQuotes::sma(n = 14),
    cryptoQuotes::sma(n = 21),
    cryptoQuotes::bollinger_bands()
  )
)

cryptocurrency charts in R

Colorblind friendly version

Charting with indicators (colorblind friendly)

## Chart BTC
## using klines, SMA
## Bollinger Bands and 
## ling-short ratio with color-deficiency
cryptoQuotes::chart(
  ticker = BTC,
  main   = cryptoQuotes::kline(),
  sub    = list(
    cryptoQuotes::lsr(ratio = BTC_LS),
    cryptoQuotes::volume()
  ),
  indicator = list(
    cryptoQuotes::sma(n = 7),
    cryptoQuotes::sma(n = 14),
    cryptoQuotes::sma(n = 21),
    cryptoQuotes::bollinger_bands()
  ),
  options = list(
    deficiency = TRUE
  )
)
cryptocurrency charts in R

ℹ️ Installation

🛡️ Stable version

## install from CRAN
install.packages(
  pkgs = 'cryptoQuotes',
  dependencies = TRUE
)

🛠️ Development version

## install from github
devtools::install_github(
  repo = 'https://github.com/serkor1/cryptoQuotes/',
  ref  = 'development'
)

ℹ️ Code of Conduct

Please note that the cryptoQuotes project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

cryptoquotes's People

Contributors

jjhvive avatar serkor1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

cryptoquotes's Issues

Expand exchange support

The following exchanges will be added to the list of available exchanges at next major release;

  • Huobi
  • Crypto.com
  • [ ]~~ OKX~~
  • MEXC

⚠️ ** Note:** This will reduce the test coverage unless there is a corresponding increase in supported indicators, or adjacent functionalities, and prevent a possible rOpenSci-admission.

⚠️ OKX only returns at maximum 100 rows of data. This is not enough, and would require a new setup of returned number of rows of get_quotes. So this exchange will get dropped.

MACOSX bug?

Hello,

I'm unable to install the package under MACOSX. However, it works fine under Windows. See the error message below,

ERROR: lazy loading failed for package ‘cryptoQuotes’

  • removing ‘/Users/andreltr/Library/R/x86_64/4.2/library/cryptoQuotes’

The downloaded source packages are in
‘/private/var/folders/xg/n17vb1ts5bv8rpn3qypd61y40000gn/T/RtmplhlRV4/downloaded_packages’
Warning message:
In install.packages(pkgs = "cryptoQuotes", dependencies = TRUE) :
installation of package ‘cryptoQuotes’ had non-zero exit status
R> library(cryptoQuotes)
Error in library(cryptoQuotes) :
there is no package called ‘cryptoQuotes’
R>

What could be its cause, please?

TIA,

André Luiz

[BUG] Warning in `chart`-function when using namespace qualified function calls

When using pkg::foo() the chart()-function throws a warning. See below,

Function calls

# 1) load library
# and define data for
# MWE
library(cryptoQuotes)

ticker  <- cryptoQuotes:::control_data$quote
lsratio <- cryptoQuotes:::control_data$lsratio

# 2) chart with 
# function calls
chart(
  ticker = ticker,
  main   = kline(),
  sub = list(
    volume()
  )
)

Namespace qualified function calls

# 3) chart with 
# namespace qualified
# function calls
cryptoQuotes::chart(
  ticker = ticker,
  main   = cryptoQuotes::kline(),
  sub = list(
    cryptoQuotes::volume()
  )
)
#> Warning in call_stack == calling_function: longer object length is not a
#> multiple of shorter object length
#> Warning in call_stack == calling_function: longer object length is not a
#> multiple of shorter object length

Created on 2024-06-05 with reprex v2.1.0

Note to self

  • This warning wouldn't get caught in the test-environment as all tests uses function calls, however all related tests should be wrapped in testthat::expect_no_condition() either way.

  • There is no legend in either example

A TODO-list of originally unplanned updates

This TODO-list is a by-product of the development of the cryptoQuotes-wiki, and covers all updates that weren't originally planned.

  • BitMart supports up to 200 data points - but needs to be added via the limit parameter before next release.
  • Binance supports up to 750 (SPOT) and 1500 (FUTURES) - but needs to be added via the limit parameter before next release.
  • remove dependency on httr2 and use curl instead. See this relevant discussion
  • stopifnot() on calls that exceed the limits of each exchange to avoid ambiguous error-messages. This has been cancelled to avoid too many checks. Users will be referred to the wiki, vignettes and general documentation.

Known Bugs and Issues in version 1.3.0

Issues

Issues are anomalies that doesn't, necessarily, break the R-package.

Fear and Greed Index Description Issue

The get_fgindex()-function is not deprecated. This will be fixed in version 1.3.1,

cryptoQuotes/R/get_fgi.R

Lines 12 to 18 in df5c565

#' @description
#'
#' `r lifecycle::badge("deprecated")`
#'
#' The fear and greed index is a market sentiment indicator that measures investor emotions to
#' gauge whether they are generally fearful (indicating potential selling pressure) or greedy (indicating potential buying enthusiasm)
#'

  • fixed

Section "Limitations" Issue

The example in the "Limitations"-section uses 30m granularity, and it seems that kraken has a lower limit on the date which is a function of the granularity. See, for example, the wiki for a similar example for 1h granularity. There is nothing about this on the exchange docs, so it is indeed an unexpected error. The following section of the article has to be changed from 30m to 1h,

```{r}
## 1) create date
## sequence
dates <- seq(
from = as.POSIXct(Sys.Date()),
by = "-30 mins",
length.out = 1440
)
## 2) split the sequence
## in multiples of 100
## by assigning numbers
## to each indices of 100
idx <- rep(
x = 1:2,
each = 720
)
## 3) use the idx to split
## the dates into equal parts
split_dates <- split(
x = dates,
f = idx
)
## 4) collect all all
## calls in a list
## using lapply
ohlc <- lapply(
X = split_dates,
FUN = function(dates){
Sys.sleep(1)
cryptoQuotes::get_quote(
ticker = "BTCUSD",
source = "kraken",
futures = FALSE,
interval = "30m",
from = min(dates),
to = max(dates)
)
})
## 4.1) rbind all
## elements
nrow(
ohlc <- do.call(
what = rbind,
args = ohlc
)
)
```

  • fixed

Error in Vignette

Dogecoin rallied 20% at the minute of the tweet. But in the vignette it shows -0.15%.

The source of the error is currently unkown.

  • fixed

Warning in get_lsr

## long-short ratio
## Binance
cryptoQuotes::get_lsratio(
  "BTCUSDT",
  interval = "15m",
  source = "binance"
)
#> In (function (...)  : 'tzone' attributes are inconsistent

This warning is displayed for all intervals, and only for binance. The source of the problem is currently unknown but was not present before 1.3.0.

  • fixed

Broken Code

Charting Long-Short Ratios

The new structure of the returned quotes with the get_lsr()-function broke lsr()-chart, due to how variables are retrieved.

cryptoQuotes/R/chart_lsr.R

Lines 83 to 109 in df5c565

plotly::layout(
yaxis = list(
title = 'Long-Short Ratio'
),
p = plotly::plot_ly(
showlegend = FALSE,
data = ratio,
y = ~ls_ratio,
x = ~Index,
type = 'scatter',
mode = 'lines+markers',
line = list(
color = 'gray',
dash = 'dash',
shape = 'spline',
smoothing = 1.5
),
marker = list(
size = 10,
color = ~color_scale,
line = list(
color = 'black',
width = 2
)
)
)
)

  • fixed

Prepare version 1.3.1 for release

Note: This is a temporary release list

Features

Add binance.us to the exchange lists

This is a trivial addition, and only requires a change in the baseurl.

  • [ ] Done!

NOTE: This won't be implemented as binance.us doesn't support perpetual futures. It would require an entirely new api_binanceus.R-file, which isn't worth the trouble for spot market only.

Custom Charting Function

Create a charting function that adds custom TAs on the chart.

  • [ ] Done!

NOTE: This will be implemented as an experimental feature once the chart-functions has been finalized and considered stable.

New Price Chart

Add a line-chart with flexible price.

  • Done!

Backend

Remove rlang-dependency

All chart-function are currently using rlang for lazy evaluation. To maintain long term stability the library will use base R lazy evaluation instead.

  • Done!

Flexible charting

All chart-functions should work with all OHLC-data, regardless of the used library

  • Done!

Bugfixes

See #9

  • Done!

Documentation

Justification

The current use-case is too simple, and the difference across library retrieving cryptocurrencies are too blurry, even though the difference is significant. To account for this, the README, wiki and/or pkgdown should be modified.

Possible subjects

  • Developping trading strategies for other than daily data.

  • Sentiment data

  • Done!

Rework Documentation

The documentation has to be more extensive and concise.

  • Done!

Release cryptoQuotes 1.2.1

Prepare for release:

  • git pull
  • Check current CRAN check results
  • Polish NEWS
  • urlchecker::url_check()
  • devtools::build_readme()
  • devtools::check(remote = TRUE, manual = TRUE)
  • devtools::check_win_devel()
  • #5
  • Update cran-comments.md
  • git push

Submit to CRAN:

  • usethis::use_version('patch')
  • devtools::submit_cran()
  • Approve email

Wait for CRAN...

  • Accepted 🎉
  • usethis::use_github_release()
  • usethis::use_dev_version(push = TRUE)

[BUG] Error in some of the MEXC intervals

Some of the MEXC intervals throws an error see below,

To Reproduce

library(cryptoQuotes)
sapply(
  X = available_intervals(
    source = "mexc",
    futures = TRUE
  ),
  FUN = function(x) {

    Sys.sleep(2)

    tryCatch(
      {
        get_quote(
          ticker   = "BTC_USDT",
          interval = x,
          source   = "mexc",
          futures  = TRUE
        )

        paste("OK in", x)
      }

      ,
      error = function(error_msg) {

        paste("Error in", x)

      },
      finally = "sd"
    )

  }
)
#>            1m            5m           15m           30m            1h 
#> "Error in 1m"    "OK in 5m"   "OK in 15m"   "OK in 30m"    "OK in 1h" 
#>            4h            8h            1d            1w            1M 
#>    "OK in 4h"    "OK in 8h"    "OK in 1d"    "OK in 1w" "Error in 1M"
sapply(
  X = available_intervals(
    source = "mexc",
    futures = FALSE
  ),
  FUN = function(x) {
    
    Sys.sleep(2)
    
    tryCatch(
      {
        get_quote(
          ticker   = "BTCUSDT",
          interval = x,
          source   = "mexc",
          futures  = FALSE
        )
        
        paste("OK in", x)
      }
      
      ,
      error = function(error_msg) {
        
        paste("Error in", x)
        
      }
    )
    
  }
)
#>            1m            5m           15m           30m            1h 
#> "Error in 1m"    "OK in 5m"   "OK in 15m"   "OK in 30m" "Error in 1h" 
#>            4h            1d            1w            1M 
#>    "OK in 4h"    "OK in 1d" "Error in 1w" "Error in 1M"

Created on 2024-06-30 with reprex v2.1.0

Expected behavior

The API are uniform in the intervals, so this error should be persistent across all intervals.


Check the following:

  • Does the working intervals return the correct intervals?
  • Is there any breaking changes to the API-documentation since it got introduced to {cryptoQuotes}

If this error persists, MEXC should either be removed completely from the package or the intervals should be remove.

Note

In either case, you should write the devs and inform them if this is a bug on their side.

Release cryptoQuotes 1.3.1

Prepare for release:

  • git pull
  • Check current CRAN check results
  • Polish NEWS
  • urlchecker::url_check()
  • devtools::build_readme()
  • devtools::check(remote = TRUE, manual = TRUE)
  • devtools::check_win_devel()
  • revdepcheck::revdep_check(num_workers = 4)
  • Update cran-comments.md
  • git push

Submit to CRAN:

  • usethis::use_version('patch')
  • devtools::submit_cran()
  • Approve email

Wait for CRAN...

  • Accepted 🎉
  • usethis::use_github_release()
  • usethis::use_dev_version(push = TRUE)

Release cryptoQuotes 1.0.0

First release:

Prepare for release:

  • git pull
  • Check if any deprecation processes should be advanced, as described in Gradual deprecation
  • urlchecker::url_check()
  • devtools::build_readme()
  • devtools::check(remote = TRUE, manual = TRUE)
  • devtools::check_win_devel()
  • git push
  • Draft blog post

Submit to CRAN:

  • usethis::use_version('major')
  • devtools::submit_cran()
  • Approve email

Wait for CRAN...

  • Accepted 🎉
  • Add preemptive link to blog post in pkgdown news menu
  • usethis::use_github_release()
  • usethis::use_dev_version(push = TRUE)
  • usethis::use_news_md()
  • Finish blog post
  • Tweet

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.