Git Product home page Git Product logo

binancer's Introduction

binancer

An R client to the Public Rest API for Binance.

API docs: https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md

Quick intro to using binancer by getting the most recent ~USD price of the cryptocurrencies supported on Binance:

library(binancer)
binance_coins_prices()

Getting data on a specific symbol pair, e.g. the most recent Bitcoin/USDT changes:

(klines <- binance_klines('BTCUSDT', interval = '1m'))

Visualize this data, e.g. on a simple line chart:

library(ggplot2)
ggplot(klines, aes(close_time, close)) + geom_line()

Poor man's candle chart with some ggplot2 tweaks:

library(scales)
ggplot(klines, aes(open_time)) +
  geom_linerange(aes(ymin = open, ymax = close, color = close < open), size = 2) +
  geom_errorbar(aes(ymin = low, ymax = high), size = 0.25) +
  theme_bw() + theme('legend.position' = 'none') + xlab('') +
  ggtitle(paste('Last Updated:', Sys.time())) +
  scale_y_continuous(labels = dollar) +
  scale_color_manual(values = c('#1a9850', '#d73027')) # RdYlGn

Extend this to multiple pairs in the past 24 hours using 15 mins intervals:

library(data.table)
klines <- rbindlist(lapply(
  c('ETHBTC', 'ARKBTC', 'NEOBTC', 'IOTABTC'),
  binance_klines,
  interval = '15m',
  limit = 4*24))
ggplot(klines, aes(open_time)) +
  geom_linerange(aes(ymin = open, ymax = close, color = close < open), size = 2) +
  geom_errorbar(aes(ymin = low, ymax = high), size = 0.25) +
  theme_bw() + theme('legend.position' = 'none') + xlab('') +
  ggtitle(paste('Last Updated:', Sys.time())) +
  scale_color_manual(values = c('#1a9850', '#d73027')) +
  facet_wrap(~symbol, scales = 'free', nrow = 2)

binancer's People

Contributors

daroczig avatar madsurgeon 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  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  avatar  avatar

Watchers

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

binancer's Issues

Adaptability to other exchanges API (bybit, kucoin...)

First, let me thank you for the work you've done with binancer package.
It works great, and I'am using it a lot for research purpose.

Question is not really an issue but mostly a request/question.
(I already asked the question on stackoverflow first but I didnt get answers).

I'd like to get similar historical crypto data 'klines' for other exchanges, such as Kucoin or Bybit.
I tried to look in your functions codes but I failed on adapting your code to other exchanges API.
Would you have an idea how to proceed please ?

Thank you,
Greg

Error in New Order Request

I found an issue with placing orders using the "new order" function.

Line 723 of "binancer/R/binance.R" reads the following:

work around the limitation of %% (e.g. 200.1 %% 0.1 = 0.1 !!)

quot <- (quantity - filters[filterType == 'LOT_SIZE', minQty]) / filters[filterType == 'LOT_SIZE', stepSize]
stopifnot(abs(quot - round(quot)) < 1e-10)

Filters, is a data table specifying some of the order limits (ie max price, max quantity, etc). Filters are specific to each coin. Using the example of "BTCUSDT", the filters value for

filters[filterType == 'LOT_SIZE', stepSize] is 0. When you evaluate quot, it yields quot = x / 0.

With that, it is not possible to successfully evaluate 'abs(quot - round(quot)) < 1e-10'.

Is there any workaround to this issue?

Much appreciated!

Partial Retrieval of my Coin Assets

Hello,
After setting

binance_credentials(key, secret)

with my binance key and secret, I call

binance_balances()

but this way I get a table which does not list all my assets on binance (only 9 coins out of 22).

I get exactly the same results using the bare bone code at

https://stackoverflow.com/a/70270748/2952838

In both cases the issue is that my flexible holdings are correctly detected, but my locked holdings (in my case staked products) are not. I believe the issue is solvable thanks to the announcement I see here

https://docs.binance.us/?python#get-staking-asset-information

but I am no API expert myself. Could this feature be added?

Thanks!

Many thanks!

Error using binance_all_orders()

Hi,

I've encountered a problem using binance_all_orders() function, where when using a specific symbol I get the following error:

"Error in rbindlist(ord) :
Item 20 has 22 columns, inconsistent with item 1 which has 20 columns. To fill missing columns use fill=TRUE."

Upon debuging the function the problem appears to be that within the function when queriyng all orders using "binance_query(endpoint = "api/v3/allOrders", params = params, sign = TRUE)" which returns a nested list with all orders. The orders of type "TAKE_PROFIT_LIMIT" has 22 items as oposed to the 20 items of the rest of the orders.

Using fill = TRUE in the rbindlist() within the function appears to fix the problem just fine if the desired behaviour is to add the 2 aditional columns to the data.frame (will be NULL in all orders except on the "TAKE_PROFIT_LIMIT")

Cheers!

New_order error

When submitting a new order

binance_new_order("CHRUSDT", side = "BUY", type = "LIMIT", quantity = 40,     price = bidask$bid_price, time_in_force = 'GTC') 

I get this back


TEST
   ord
1:  OK

It does not complete the order and I dont understand why? Thanks for any advise.

Where to put API Key & Secret Key Variables

Firstly, I want to thank you for sharing this script.

However, I couldn't able to run the script. Actually, I couldn't find where to put the API Key & Secret Keys and which function should I run first. Could you please provide a bit more detail in Readme?

Thank you.

Binance US API

Hello,

Is there any way you can edit this package to allow me to everything I can now but with Binance US?

get_kline not pulling codes from a string

The following error when calling get_klines for a string

> prices_symbols_selected <- get_klines(c("ETHBTC", "LTCBTC"), "1d", limit = 200)
ERROR [2018-01-19 09:30:03] Binance query to api/v1/klines failed for the NAst/nd/rd/th time, retrying
Error in if (isTRUE(retry) & retries < 4) { : argument is of length zero

Error in binance_new_order type = "MARKET"

Hello!

@daroczig @stanyip

This error is ocurred in binance_new_order(symbol = symbol,
side = "SELL",
type = "MARKET",
quantity = quantity,
test = FALSE)

Error in [.data.table(filters, filterType == "MIN_NOTIONAL", applyToMarket) :
j (the 2nd argument inside [...]) is a single symbol but column name 'applyToMarket' is not found. Perhaps you intended DT[, ..applyToMarket]. This difference to data.frame is deliberate and explained in FAQ 1.1.
Calls: binance_new_order -> isTRUE -> [ -> [.data.table

Error when creating new orders

I keep getting the below error when attempting to add new orders:

abs(quot - round(quot)) < 1e-10 is not TRUE

Does anyone know how to solve this issue?

Help on sign in

Need some help with sign in:

After adding credentials, I am getting the following error

> binance_sign()
Error in binance_sign() : argument "params" is missing, with no default

What is the right way to start? I am willing to contribute with the documentation. Just need some guidance to start with

most functions don't work

> binance_coins()
No encoding supplied: defaulting to UTF-8.
Error in `[.data.table`(binance_exchange_info()$symbols, status == "TRADING",  : 
  j (the 2nd argument inside [...]) is a single symbol but column name 'symbol' is not found. Perhaps you intended DT[, ..symbol]. This difference to data.frame is deliberate and explained in FAQ 1.1.
> binance_coins_prices(unit = "USDT")
Error in if (BINANCE_WEIGHT > 1159) { : argument is of length zero
> binance_klines('ETHUSDT')
Error in if (BINANCE_WEIGHT > 1159) { : argument is of length zero
> binance_symbols(all = FALSE)
Error in if (BINANCE_WEIGHT > 1159) { : argument is of length zero
> binance_ticker_24hr('ARKETH')
Error in if (BINANCE_WEIGHT > 1159) { : argument is of length zero

Error using Binance.us API

Hi, I used this library before without issues, but lately, I have encountered some issues. For example, when I run binance_ping(), I get:

Error in if (BINANCE_WEIGHT > 1159) { : argument is of length zero

At some point, I got a message related to eligibility, and it took me to the binance.com site (I haven't been able to replicate it, sorry), which made me think it is a binance.us vs binance.com issue.

I tried modifying the code locally and changing the API URL to api.binance.us, and now I get a new error:

Error in config() : could not find function "config"

I assume there is something going on since binance.us started having issues. In any case, is there any guidance you can think of to correct this?

Thanks!

Possible to check the oldest info for a given market?

If I use the below code I get the coin history as desired:
binance_klines("ETHUSDT", interval = "1m", start_time = as.POSIXct("2018-01-01"), end_time = as.POSIXct("2018-01-02"), limit=100)

However, if I use a too old date, an error is returned:
binance_klines("ETHUSDT", interval = "1m", start_time = as.POSIXct("2017-01-01"), end_time = as.POSIXct("2017-01-02"), limit=100)

Error in `[.data.table`(klines, , -12) : 
  Item 1 of j is 12 which is outside the column number range [1,ncol=0]

Is there a way to find what would be the oldest date that is possible to retrieve from a coin history with binancer functions?

Binancer not available for R 3.6.3

Hi,

when I try to install your package, I get this message:

Warning in install.packages :
  package ‘binancer’ is not available (for R version 3.6.3)

Warning message:
  there is no package called ‘binancer’

Error in Retrieving Coin Price in USDT

Hello,

I do not know if the project is still active, given the number of issues which have not been reacted upon in months, but I would like to signal a bug. Specifically it is for the retrieval of the USDT price of the CRL token.

Please have a look at the reprex below.

library(binancer)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df <- binance_coins_prices() |>
    as_tibble()

df
#> # A tibble: 1,440 × 2
#>    symbol       usd
#>    <chr>      <dbl>
#>  1 ETH    3371.    
#>  2 LTC      75.7   
#>  3 BNB     417.    
#>  4 NEO      14.0   
#>  5 QTUM      3.72  
#>  6 EOS       0.855 
#>  7 SNT       0.0450
#>  8 BNT       0.885 
#>  9 BCC    4835.    
#> 10 GAS       6.55  
#> # ℹ 1,430 more rows

crv_price <- df |>
    filter(symbol=="CRV")

crv_price
#> # A tibble: 1 × 2
#>   symbol   usd
#>   <chr>  <dbl>
#> 1 CRV     2.87

##this price is simply wrong. As of now (28/02/2024) the price
#of crv in usdt is around 0.6

## Try to understand where this comes from. binance_coins_prices relies on
## binance_ticker_all_prices


df2 <- binance_ticker_all_prices() |>
    as_tibble()

df2
#> # A tibble: 2,493 × 6
#>    symbol      price from   from_usd to    to_usd
#>    <chr>       <dbl> <chr>     <dbl> <chr>  <dbl>
#>  1 ETHBTC  0.0551    ETH   3371.     BTC   61135.
#>  2 LTCBTC  0.00124   LTC     75.7    BTC   61135.
#>  3 BNBBTC  0.00682   BNB    417.     BTC   61135.
#>  4 NEOBTC  0.000229  NEO     14.0    BTC   61135.
#>  5 QTUMETH 0.00111   QTUM     3.72   ETH    3371.
#>  6 EOSETH  0.000254  EOS      0.855  ETH    3371.
#>  7 SNTETH  0.0000134 SNT      0.0450 ETH    3371.
#>  8 BNTETH  0.000263  BNT      0.885  ETH    3371.
#>  9 BCCBTC  0.0791    BCC   4835.     BTC   61135.
#> 10 GASBTC  0.000107  GAS      6.55   BTC   61135.
#> # ℹ 2,483 more rows


crv <- df2 |>
    filter(from=="CRV")

crv ## so the binance_coins_prices picks the to==BNB entry by mistake
#> # A tibble: 4 × 6
#>   symbol      price from  from_usd to    to_usd
#>   <chr>       <dbl> <chr>    <dbl> <chr>  <dbl>
#> 1 CRVBNB  0.00687   CRV      2.87  BNB     417.
#> 2 CRVBTC  0.0000101 CRV      0.618 BTC   61135.
#> 3 CRVUSDT 0.620     CRV      0.620 USDT      1 
#> 4 CRVETH  0.000208  CRV      0.700 ETH    3371.
## Can someone fix this ?

Created on 2024-02-28 with reprex v2.0.2

new order problem (everything seems fine but order does not exist)

Hi,

I have a problem when placing a new order. This is the code I am using:

binance_new_order(symbol = "ADABUSD", side = ("SELL"), quantity = 10, price = curr_price, type = "LIMIT",
time_in_force = "GTC")

I get that:

TEST
ord
1: OK

So it looks like it worked. However, when I look at my "open orders" by using:

binance_all_orders("ADABUSD")

I get that:

Null data.table (0 rows and 0 cols)

So, it looks like the order do not exist. It do not appear in my "Open orders" in binance. The API is connected as shown by binance_ping(), so I am probably missing something here.

Any help will be very welcome! Thank you in advance.

Wallet Option

Hi,

Thank you for a great piece of code. I was wondering whether we could have the option to select a wallet. At the moment I appear to only have access to Spot, but I would prefer to trade using my margin wallet.

Is this possible please or are you aware of any other solutions for RStudio?

Many thanks,

Neil

Restricted location

require(binancer)
binance_klines('ETHUSDT')
Error in binance_query(endpoint = "api/v1/klines", params = params) : 
  0 Service unavailable from a restricted location according to 'b. Eligibility' in https://www.binance.com/en/terms. Please contact customer service if you believe you received this message in error.

Session information:

R version 4.2.3 (2023-03-15)
Platform: x86_64-redhat-linux-gnu (64-bit)
Running under: Fedora Linux 37 (Workstation Edition)

Matrix products: default
BLAS/LAPACK: /usr/lib64/libflexiblas.so.3.3

locale:
 [1] LC_CTYPE=en_US.UTF-8      
 [2] LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8       
 [4] LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8   
 [6] LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8      
 [8] LC_NAME=C                 
 [9] LC_ADDRESS=C              
[10] LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8
[12] LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets 
[6] methods   base     

other attached packages:
[1] binancer_1.2.0

loaded via a namespace (and not attached):
 [1] httr_1.4.5        compiler_4.2.3   
 [3] logger_0.2.2      R6_2.5.1         
 [5] snakecase_0.11.0  tools_4.2.3      
 [7] glue_1.6.2        rstudioapi_0.14  
 [9] curl_5.0.0        data.table_1.14.8
[11] jsonlite_1.8.4    digest_0.6.31 

BInance Futures orders

Hello, I was just wondering if there is a way to place an order in Binance Futures instead of Spot orders?

Add timeout option

With an unreliable connection calls to binance_klines() will sometimes hang and never return. The httr package supports timeout() option for the GET() function: https://rdrr.io/cran/httr/man/timeout.html

Ideally this option would be exposed in binancer or at least a sane default chosen (if there is one 😄 )

Futures data

Hi,

thanks for the great package! How can I differentiate USDT futures from spot using the functions?

Add recvWindow parameter

The default (6000) recvWindow might not be enough. I keep receiving Timestamp for this request is outside of the recvWindow.
My own test is that 20000 is a better setting.

problem creating new orders: error in filters

Hi,
I get the following error when creating a new order (e.g.: binance_new_order("XRPUSDT", side = "BUY", type = "LIMIT", price=0.32, quantity = 60, time_in_force = "GTC", test=F):

"Error in if (filters[filterType == "PERCENT_PRICE", avgPriceMins] == 0) { :
argument is of length zero"

If I run: filters <- binance_filters("XRPUSDT"), I can see that filterType has the value PERCENT_PRICE_BY_SIDE but not PERCENT_PRICE

Error in binance_mytrades()

You have an error in binance_mytrades(), you write setnames instead of setNames.

Amazing job. Thanks
Now I need 1 week to understand all this code.

Error with binance_query()

Hi all,

I am running the latest Github version of 'binancer' and when I check my account with binance_account() it gives the following error:

Error in binance_query(endpoint = "api/v3/account", sign = TRUE) : 
  -1021 Timestamp for this request is outside of the recvWindow.

Can anyone please help?

Invalid API-key, IP, or permissions for action. -2015 error code

So this error is very odd, my api key has permission to read and write on my IP I am using.

Not sure what to diagnose. I have made a new secret and key combo a few times to see if it was that but that wasnt the case,

Anyone else have this issue, or came across it before?

R version 4.1.2 (2021-11-01)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 20.04.3 LTS

Matrix products: default
BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so

locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats graphics grDevices utils datasets methods base

loaded via a namespace (and not attached):
[1] httr_1.4.2 compiler_4.1.2 logger_0.2.2 R6_2.5.1 snakecase_0.11.0 tools_4.1.2
[7] glue_1.6.1 binancer_1.2.0 curl_4.3.2 data.table_1.14.2 jsonlite_1.7.3 digest_0.6.29

Timestamp error

I would like to add some functionality to the package, but somehow I'm only allowed to make 1 request to the API. I have to restart R in order to access it again.

key <-  "xx"
secret <- "xxx"
binance_credentials(key, secret)

## The first request works fine
binance_account()
## The second throws an error
binance_balances()

Error in eval(jsub, SDenv, parent.frame()) : object 'free' not found

The binance_balances function obviously gets stuck with the binance_account function. It throws the following timestamp error:

binance_account()

1: -1021 Timestamp for this request was 1000ms ahead of the server's time.

Actually, I found some solutions by analyzing it :)
If you include a Sys.sleep(2) just before the query() in the binance_query function, it runs! But makes the code slower. If you adapt the timestamp function to this, it runs faster.
timestamp <- function() { as.character(round(as.numeric(Sys.time()) * 1e3)-2000) }

The code runs obviously too fast and is ahead of time ;)

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.