-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathbinance.R
1061 lines (869 loc) · 31.9 KB
/
binance.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
BINANCE <- list(
TYPE = c('LIMIT', 'MARKET',
'STOP_LOSS', 'STOP_LOSS_LIMIT',
'TAKE_PROFIT', 'TAKE_PROFIT_LIMIT',
'LIMIT_MAKER'),
SIDE = c('BUY', 'SELL'),
TIMEINFORCE = c('GTC', 'IOC', 'FOK'),
INTERVALS = c(
'1m', '3m', '5m', '15m', '30m',
'1h', '2h', '4h', '6h', '8h', '12h',
'1d', '3d', '1w', '1M'),
METHODS = c('GET', 'POST', 'PUT', 'DELETE')
)
BINANCE_WEIGHT <- 0
# Utils -------------------------------------------------------------------
#' Look up Binance API secret stored in the environment
#' @return string
#' @keywords internal
binance_secret <- function() {
binance_check_credentials()
credentials$secret
}
#' Look up Binance API key stored in the environment
#' @return string
#' @keywords internal
binance_key <- function() {
binance_check_credentials()
credentials$key
}
#' Sets the API key and secret to interact with the Binance API
#' @param key string
#' @param secret string
#' @export
#' @return No return values, setting config in the package namespace.
#' @examples \dontrun{
#' binance_credentials('foo', 'bar')
#' }
binance_credentials <- function(key, secret) {
credentials$key <- key
credentials$secret <- secret
}
#' Check if Binance credentials were set previously
#' @return No return values, but fails when credentials were not set.
#' @keywords internal
binance_check_credentials <- function() {
if (is.null(credentials$secret)) {
stop('Binance API secret not set? Call binance_credentials()')
}
if (is.null(credentials$key)) {
stop('Binance API key not set? Call binance_credentials()')
}
}
#' Sign the query string for Binance
#' @param params list
#' @return string
#' @keywords internal
#' @importFrom digest hmac
#' @examples \dontrun{
#' signature(list(foo = 'bar', z = 4))
#' }
binance_sign <- function(params) {
params$timestamp <- timestamp()
params$signature <- hmac(
key = binance_secret(),
object = paste(
mapply(paste, names(params), params, sep = '=', USE.NAMES = FALSE),
collapse = '&'),
algo = 'sha256')
params
}
#' Request the Binance API
#' @param endpoint string
#' @inheritParams query
#' @param sign if signature required
#' @param content_as parameter to httr::content
#' @return R object
#' @keywords internal
#' @importFrom httr headers add_headers content
#' @importFrom utils assignInMyNamespace
binance_query <- function(endpoint, method = 'GET',
params = list(), body = NULL, sign = FALSE,
retry = method == 'GET', content_as = 'parsed') {
# if Binance weight is approaching the limit of 1200, wait for the next full minute
if (BINANCE_WEIGHT > 1159) {
Sys.sleep(61 - as.integer(format(Sys.time(), "%S")))
}
method <- match.arg(method)
if (isTRUE(sign)) {
params <- binance_sign(params)
config <- add_headers('X-MBX-APIKEY' = binance_key())
} else {
config <- config()
}
res <- query(
base = 'https://api.binance.com',
path = endpoint,
method = method,
params = params,
config = config)
assignInMyNamespace('BINANCE_WEIGHT', as.integer(headers(res)$`x-mbx-used-weight`))
res <- content(res, as = content_as)
if (content_as == 'parsed' & length(res) == 2 & !is.null(names(res))) {
if (all(names(res) == c('code', 'msg'))) {
stop(paste(res, collapse = ' '))
}
}
res
}
formals(binance_query)$method <- BINANCE$METHODS
#' Test connectivity to the Rest API
#' @export
#' @return "OK" string on success
binance_ping <- function() {
res <- binance_query(endpoint = '/api/v1/ping')
if (is.list(res) & length(res) == 0) {
res <- 'OK'
}
res
}
#' Get the current server time from Binance
#' @export
#' @return \code{POSIXct}
binance_time <- function() {
res <- binance_query(endpoint = '/api/v1/time')$serverTime
res <- as.POSIXct(res/1e3, origin = '1970-01-01')
res
}
# Stats -------------------------------------------------------------------
#' Get kline/candlestick data from Binance
#' @param symbol string
#' @param interval enum
#' @param limit optional int
#' @param start_time optional POSIX timestamp
#' @param end_time optional POSIX timestamp
#' @return \code{data.table} with open-high-low-close values
#' @export
#' @importFrom data.table rbindlist data.table :=
#' @examples \dontrun{
#' binance_klines('ETHUSDT')
#' binance_klines('ETHUSDT', interval = '1h', limit = 24*7)
#' binance_klines('ETHUSDT', interval = '1h', start_time = '2018-01-01', end_time = '2018-01-08')
#' }
binance_klines <- function(symbol, interval, limit, start_time, end_time) {
interval <- match.arg(interval)
params <- list(symbol = symbol,
interval = interval)
if (!missing(limit)) {
stopifnot(limit <= 1000L)
params$limit <- limit
}
if (!missing(start_time)) {
params$startTime <- format(as.numeric(as.POSIXct(start_time)) * 1e3, scientific = FALSE)
}
if (!missing(end_time)) {
params$endTime <- format(as.numeric(as.POSIXct(end_time)) * 1e3, scientific = FALSE)
}
klines <- binance_query(endpoint = 'api/v1/klines', params = params)
klines <- rbindlist(klines)
# drop last dummy column
klines <- klines[, -12]
names(klines) <- c(
'open_time',
'open',
'high',
'low',
'close',
'volume',
'close_time',
'quote_asset_volume',
'trades',
'taker_buy_base_asset_volume',
'taker_buy_quote_asset_volume'
)
for (v in setdiff(names(klines), c('open_time', 'close_time', 'trades'))) {
klines[, (v) := as.numeric(get(v))]
}
for (v in c('open_time', 'close_time')) {
klines[, (v) := as.POSIXct(get(v)/1e3, origin = '1970-01-01')]
}
# return
klines[, symbol := symbol]
data.table(klines)
}
formals(binance_klines)$interval <- BINANCE$INTERVALS
#' Get tick data from Binance
#' @param symbol string
#' @param from_id optional number
#' @param start_time optional POSIX timestamp
#' @param end_time optional POSIX timestamp
#' @param limit optional int
#' @return \code{data.table}
#' @export
#' @importFrom data.table rbindlist data.table
#' @examples \dontrun{
#' binance_ticks('ETHUSDT')
#' binance_ticks('ETHUSDT', start_time = '2018-01-01 00:00:00', end_time = '2018-01-01 01:00:00')
#' }
binance_ticks <- function(symbol, from_id, start_time, end_time, limit) {
# silence "no visible global function/variable definition" R CMD check
time <- NULL
params <- list(symbol = symbol)
if (!missing(limit)) {
stopifnot(limit <= 1000L)
params$limit <- limit
}
if (!missing(from_id)) {
# work around RCurl issue
# see https://github.com/daroczig/binancer/pull/9#issuecomment-517916493
params$fromId <- as.character(from_id)
}
if (!missing(start_time)) {
params$startTime <- format(as.numeric(as.POSIXct(start_time)) * 1e3, scientific = FALSE)
}
if (!missing(end_time)) {
if (!missing(start_time)) {
stopifnot(as.numeric(difftime(end_time, start_time, units = 'secs')) <= 3600)
}
params$endTime <- format(as.numeric(as.POSIXct(end_time)) * 1e3, scientific = FALSE)
}
ticks <- binance_query(endpoint = 'api/v1/aggTrades', params = params)
if (length(ticks) > 0) {
ticks <- rbindlist(ticks)
names(ticks) <- c(
'agg_trade_id',
'price',
'quantity',
'first_trade_id',
'last_trade_id',
'time',
'buyer_maker',
'best_price_match')
for (v in c('price', 'quantity')) {
ticks[, (v) := as.numeric(get(v))]
}
ticks[, time := as.POSIXct(time/1e3, origin = '1970-01-01')]
# return
ticks[, symbol := symbol]
ticks
}
}
#' Get last trades from Binance
#' @param symbol string
#' @param limit optional int
#' @return \code{data.table}
#' @export
#' @importFrom data.table rbindlist data.table
#' @importFrom snakecase to_snake_case
#' @examples \dontrun{
#' binance_trades('ETHUSDT')
#' binance_trades('ETHUSDT', limit = 1000)
#' }
binance_trades <- function(symbol, limit) {
# silence "no visible global function/variable definition" R CMD check
time <- NULL
params <- list(symbol = symbol)
if (!missing(limit)) {
stopifnot(limit <= 1000L)
params$limit <- limit
}
trades <- binance_query(endpoint = 'api/v1/trades', params = params)
trades <- rbindlist(trades)
for (v in c('price', 'qty', 'quoteQty')) {
trades[, (v) := as.numeric(get(v))]
}
trades[, time := as.POSIXct(time/1e3, origin = '1970-01-01')]
trades[, symbol := symbol]
# return with snake_case column names
setnames(trades, to_snake_case(names(trades)))
trades
}
#' Get orderbook depth data from Binance
#' @param symbol string
#' @param limit int optional
#' @return \code{data.table}
#' @export
#' @importFrom data.table rbindlist data.table
#' @examples \dontrun{
#' binance_depth('ETHUSDT')
#' binance_depth('ETHUSDT', limit = 1000)
#' }
binance_depth <- function(symbol, limit) {
params <- list(symbol = symbol)
if (!missing(limit)) {
stopifnot(limit %in% c(5, 10, 20, 50, 100, 500, 1000, 5000))
params$limit <- limit
}
depth <- binance_query(endpoint = 'api/v1/depth', params = params)
bids <- rbindlist(depth$bids)
asks <- rbindlist(depth$asks)
names(bids) <- c(
'price',
'quantity')
names(asks) <- c(
'price',
'quantity')
for (v in names(bids)) {
bids[, (v) := as.numeric(get(v))]
}
for (v in names(asks)) {
asks[, (v) := as.numeric(get(v))]
}
# return
depth$bids <- bids
depth$asks <- asks
depth
}
# Ticker data -------------------------------------------------------------
#' Get last price for a symbol or all symbols
#' @param symbol optional string
#' @return \code{data.table}
#' @export
binance_ticker_price <- function(symbol) {
# silence "no visible global function/variable definition" R CMD check
price <- NULL
if (!missing(symbol)) {
params <- list(symbol = symbol)
res <- binance_query(endpoint = 'api/v3/ticker/price', params = params)
res <- as.data.table(res)
} else {
res <- binance_query(endpoint = 'api/v3/ticker/price')
res <- rbindlist(res)
}
res[, price := as.numeric(price)]
res
}
#' Get last bids and asks for a symbol or all symbols
#' @param symbol optional string
#' @return \code{data.table}
#' @export
#' @importFrom snakecase to_snake_case
binance_ticker_book <- function(symbol) {
if (!missing(symbol)) {
params <- list(symbol = symbol)
res <- binance_query(endpoint = 'api/v3/ticker/bookTicker', params = params)
res <- as.data.table(res)
} else {
res <- binance_query(endpoint = 'api/v3/ticker/bookTicker')
res <- rbindlist(res)
}
for (v in setdiff(names(res), 'symbol')) {
res[, (v) := as.numeric(get(v))]
}
# return with snake_case column names
setnames(res, to_snake_case(names(res)))
res
}
#' Get latest Binance conversion rates and USD prices on all symbol pairs
#' @return \code{data.table}
#' @export
#' @importFrom data.table rbindlist
binance_ticker_all_prices <- function() {
# silence "no visible global function/variable definition" R CMD check
price <- from <- to <- to_usd <- from_usd <- symbol <- NULL
prices <- binance_ticker_price()
# split from/to
prices <- merge(
prices,
binance_exchange_info()$symbols[, .(symbol, from = baseAsset, to = quoteAsset)],
by = 'symbol', all.x = TRUE, all.y = FALSE)
# prices of seasoned stablecoins
prices[to %in% c('USDT'), to_usd := 1]
prices[from %in% c('USDT'), to_usd := 1/price]
# recursive resolve prices
while (prices[, any(is.na(to_usd))]) {
lookup <- prices[!is.na(to_usd)][, .(price = mean(to_usd)), by = .(symbol = to)]
## fall back to previously looked up/double conversions
lookup <- rbind(
lookup,
prices[!from %in% lookup$symbol & !is.na(to_usd)][
, .(price = mean(price * to_usd)), by = .(symbol = from)])
for (s in
intersect(
## missing symbols
prices[is.na(to_usd), unique(to)],
## symbols with known data
lookup[, symbol]
)) {
prices[is.na(to_usd) & to == s, to_usd := lookup[symbol == s, price]]
prices[is.na(to_usd) & from == s, to_usd := lookup[symbol == s, price]]
}
}
# from price should be always based on USDT when available
prices <- merge(
prices,
prices[to == 'USDT', .(from, from_usd = price)],
by = 'from', all.x = TRUE, all.y = FALSE)
# when direct USDT conversion not available, use avg of all lookups
lookup <- prices[is.na(from_usd), .(price = mean(price * to_usd)), by = from]
for (s in lookup[, from]) {
prices[from == s & is.na(from_usd), from_usd := lookup[from == s, price]]
}
prices[, list(symbol, price, from, from_usd, to, to_usd)]
}
#' Get latest Binance bids and asks on all symbol pairs
#' @return \code{data.table}
#' @export
#' @importFrom data.table rbindlist
#' @importFrom snakecase to_snake_case
binance_ticker_all_books <- function() {
books <- binance_query(endpoint = 'api/v1/ticker/allBookTickers')
books <- rbindlist(books)
for (v in setdiff(names(books), 'symbol')) {
books[, (v) := as.numeric(get(v))]
}
# return with snake_case column names
setnames(books, to_snake_case(names(books)))
books
}
#' 24 hour rolling window price change statistics
#' @param symbol optional string
#' @return \code{data.table}
#' @export
#' @importFrom data.table rbindlist
#' @importFrom snakecase to_snake_case
#' @examples \dontrun{
#' binance_ticker_24hr('ARKETH')
#' binance_ticker_24hr() # all symbols - binance.weight 40
#' }
binance_ticker_24hr <- function(symbol) {
if (!missing(symbol)) {
params <- list(symbol = symbol)
prices <- binance_query(endpoint = 'api/v1/ticker/24hr', params = params)
prices <- as.data.table(prices)
} else {
prices <- binance_query(endpoint = 'api/v1/ticker/24hr')
prices <- rbindlist(prices)
}
for (v in setdiff(names(prices), c('symbol', 'openTime', 'closeTime', 'firstId', 'lastId', 'count'))) {
prices[, (v) := as.numeric(get(v))]
}
for (v in c('openTime', 'closeTime')) {
prices[, (v) := as.POSIXct(get(v)/1e3, origin = '1970-01-01')]
}
# return with snake_case column names
setnames(prices, to_snake_case(names(prices)))
prices
}
#' Get current average price for a symbol
#' @param symbol string
#' @return \code{data.table}
#' @export
#' @importFrom jsonlite fromJSON
binance_avg_price <- function(symbol) {
# silence "no visible global function/variable definition" R CMD check
price <- NULL
params <- list(symbol = symbol)
res <- binance_query(endpoint = '/api/v3/avgPrice', params = params)
res <- as.data.table(res)
res[, price := as.numeric(price)]
res
}
#' Get exchangeInfo from Binance
#' @return \code{list}
#' @export
#' @importFrom jsonlite fromJSON
binance_exchange_info <- function() {
res <- binance_query(endpoint = '/api/v1/exchangeInfo', content_as = 'text')
res <- fromJSON(res)
res$serverTime <- as.POSIXct(res$serverTime/1e3, origin = '1970-01-01')
res$rateLimits <- as.data.table(res$rateLimits)
res$symbols <- as.data.table(res$symbols)
res
}
#' Get current filters for a symbol
#' @param symbol string
#' @return \code{data.table}
#' @export
binance_filters <- function(symbol) {
# workaround the problem in data.table when variable has the same name as column
symb <- symbol
filters <- as.data.table(binance_exchange_info()$symbols[symbol == symb, filters][[1]])
for (v in setdiff(names(filters), c('filterType', 'avgPriceMins', 'applyToMarket', 'limit', 'maxNumAlgoOrders'))) {
filters[, (v) := as.numeric(get(v))]
}
filters
}
#' Get all currently valid symbol names from Binance
#' @param all optional bool include non-trading symbols
#' @return character vector of symbol names
#' @export
binance_symbols <- function(all = FALSE) {
# silence "no visible global function/variable definition" R CMD check
symbol <- status <- NULL
if (isTRUE(all)) {
binance_exchange_info()$symbols$symbol
} else {
binance_exchange_info()$symbols[status == 'TRADING', symbol]
}
}
#' Get all currently valid coin names from Binance
#' @return character vector of coin names
#' @export
binance_coins <- function() {
sort(unique(sub('(BTC|ETH|BNB|USDT|TUSD|PAX|USDC|XRP|USDS)$', '', binance_symbols())))
}
#' Get all currently valid coin names from Binance along with the USDT prices
#' @param unit to set quote asset
#' @return \code{data.table} with \code{symbol} and \code{usd} columns
#' @export
binance_coins_prices <- function(unit = 'USDT') {
# silence "no visible global function/variable definition" R CMD check
from <- from_usd <- NULL
unique(binance_ticker_all_prices(), by = 'from')[, list(symbol = from, usd = from_usd)]
}
# Account info ------------------------------------------------------------
#' Get current general Binance account information, without balances
#' @return data.table
#' @export
#' @importFrom data.table as.data.table
#' @importFrom snakecase to_snake_case
binance_account <- function() {
account <- binance_query(endpoint = 'api/v3/account', sign = TRUE)
account$balances <- NULL
account <- as.data.table(account)
account$updateTime <- as.POSIXct(account$updateTime/1e3, origin = '1970-01-01')
# return with snake_case column names
setnames(account, to_snake_case(names(account)))
account
}
#' Get current Binance balances in a nice table
#' @param threshold optional show assets with greater number of coins
#' @param usdt optional to include balance in USDT too
#' @return data.table
#' @export
#' @importFrom data.table rbindlist
binance_balances <- function(threshold = -1, usdt = FALSE) {
# silence "no visible global function/variable definition" R CMD check
free <- locked <- total <- usd <- NULL
balances <- binance_query(endpoint = 'api/v3/account', sign = TRUE)$balances
balances <- rbindlist(balances)
balances[, free := as.numeric(free)]
balances[, locked := as.numeric(locked)]
balances[, total := free + locked]
if (isTRUE(usdt)) {
balances <- merge(
balances, binance_coins_prices(),
by.x = 'asset', by.y = 'symbol', all.x = TRUE, all.y = FALSE)
balances[, usd := usd * total]
}
balances[total > threshold]
}
#' Get trades for a specific symbol on the Binance account
#' @param symbol string
#' @param limit optional int number of trades to fetch
#' @param from_id optional trade id to fetch from
#' @param start_time optional POSIX timestamp
#' @param end_time optional POSIX timestamp
#' @return data.table
#' @export
#' @importFrom data.table as.data.table setnames
#' @importFrom snakecase to_snake_case
#' @examples \dontrun{
#' binance_mytrades('ARKETH')
#' binance_mytrades(c('ARKBTC', 'ARKETH'))
#' }
binance_mytrades <- function(symbol, limit, from_id, start_time, end_time) {
# silence "no visible global function/variable definition" R CMD check
time <- NULL
if (length(symbol) > 1) {
return(rbindlist(lapply(symbol, binance_mytrades), fill = TRUE))
}
params <- list(symbol = symbol)
if (!missing(limit)) {
stopifnot(limit <= 1000L)
params$limit <- limit
}
if (!missing(from_id)) {
params$fromId <- from_id
}
if (!missing(start_time)) {
params$startTime <- format(as.numeric(as.POSIXct(start_time)) * 1e3, scientific = FALSE)
}
if (!missing(end_time)) {
params$endTime <- format(as.numeric(as.POSIXct(end_time)) * 1e3, scientific = FALSE)
}
trades <- binance_query(endpoint = 'api/v3/myTrades', params = params, sign = TRUE)
trades <- rbindlist(trades)
if (nrow(trades) == 0) {
return(data.table())
} else {
trades[, time := as.POSIXct(time/1e3, origin = '1970-01-01')]
}
# return with snake_case column names
setnames(trades, to_snake_case(names(trades)))
data.table(trades)
}
#' Open new order on the Binance account
#' @param symbol string
#' @param side enum
#' @param type enum
#' @param time_in_force optional enum
#' @param quantity number
#' @param price optional number
#' @param stop_price optional number
#' @param iceberg_qty optional number
#' @param test bool
#' @return data.table
#' @export
#' @importFrom snakecase to_snake_case
#' @examples \dontrun{
#' binance_new_order('ARKETH', side = 'BUY', type = 'MARKET', quantity = 1)
#' binance_new_order('ARKBTC', side = 'BUY', type = 'LIMIT', quantity = 1,
#' price = 0.5, time_in_force = 'GTC')
#' }
binance_new_order <- function(symbol, side, type, time_in_force, quantity, price, stop_price, iceberg_qty, test = TRUE) {
# silence "no visible global function/variable definition" R CMD check
filterType <- minQty <- maxQty <- stepSize <- applyToMarket <- avgPriceMins <- limit <- NULL
minNotional <- minPrice <- maxPrice <- tickSize <- multiplierDown <- multiplierUp <- NULL
side <- match.arg(side)
type <- match.arg(type)
# check for additional mandatory parameters based on type
if (type == 'LIMIT') {
stopifnot(!missing(time_in_force), !missing(price))
}
if (type == 'STOP_LOSS' | type == 'TAKE_PROFIT') {
stopifnot(!missing(stop_price))
}
if (type == 'STOP_LOSS_LIMIT' | type == 'TAKE_PROFIT_LIMIT') {
stopifnot(!missing(time_in_force), !missing(price), !missing(stop_price))
}
if (type == 'LIMIT_MAKER') {
stopifnot(!missing(price))
}
params <- list(symbol = symbol,
side = side,
type = type,
quantity = quantity)
if (!missing(time_in_force)) {
time_in_force <- match.arg(time_in_force)
params$timeInForce = time_in_force
}
# get filters and check
filters <- binance_filters(symbol)
stopifnot(quantity >= filters[filterType == 'LOT_SIZE', minQty],
quantity <= filters[filterType == 'LOT_SIZE', maxQty])
# 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)
if (type == 'MARKET') {
stopifnot(quantity >= filters[filterType == 'MARKET_LOT_SIZE', minQty],
quantity <= filters[filterType == 'MARKET_LOT_SIZE', maxQty])
# work around the limitation of %% (e.g. 200.1 %% 0.1 = 0.1 !!)
quot <- (quantity - filters[filterType == 'MARKET_LOT_SIZE', minQty]) / filters[filterType == 'MARKET_LOT_SIZE', stepSize]
stopifnot(abs(quot - round(quot)) < 1e-10)
if (isTRUE(filters[filterType == 'MIN_NOTIONAL', applyToMarket])) {
if (filters[filterType == 'MIN_NOTIONAL', avgPriceMins] == 0) {
ref_price <- binance_ticker_price(symbol)$price
} else {
ref_price <- binance_avg_price(symbol)
stopifnot(ref_price$mins == filters[filterType == 'MIN_NOTIONAL', avgPriceMins])
ref_price <- ref_price$price
}
stopifnot(ref_price * quantity >= filters[filterType == 'MIN_NOTIONAL', minNotional])
}
}
if (!missing(price)) {
stopifnot(price >= filters[filterType == 'PRICE_FILTER', minPrice])
if (filters[filterType == 'PRICE_FILTER', maxPrice] > 0) {
stopifnot(price <= filters[filterType == 'PRICE_FILTER', maxPrice])
}
if (filters[filterType == 'PRICE_FILTER', tickSize] > 0) {
# work around the limitation of %% (e.g. 200.1 %% 0.1 = 0.1 !!)
quot <- (price - filters[filterType == 'PRICE_FILTER', minPrice]) / filters[filterType == 'PRICE_FILTER', tickSize]
stopifnot(abs(quot - round(quot)) < 1e-10)
}
if (filters[filterType == 'PERCENT_PRICE', avgPriceMins] == 0) {
ref_price <- binance_ticker_price(symbol)$price
} else {
ref_price <- binance_avg_price(symbol)
stopifnot(ref_price$mins == filters[filterType == 'PERCENT_PRICE', avgPriceMins])
ref_price <- ref_price$price
}
stopifnot(
price >= ref_price * filters[filterType == 'PERCENT_PRICE', multiplierDown],
price <= ref_price * filters[filterType == 'PERCENT_PRICE', multiplierUp]
)
stopifnot(price * quantity >= filters[filterType == 'MIN_NOTIONAL', minNotional])
params$price = price
}
if (!missing(stop_price)) {
stopifnot(stop_price >= filters[filterType == 'PRICE_FILTER', minPrice])
if (filters[filterType == 'PRICE_FILTER', maxPrice] > 0) {
stopifnot(stop_price <= filters[filterType == 'PRICE_FILTER', maxPrice])
}
if (filters[filterType == 'PRICE_FILTER', tickSize] > 0) {
# work around the limitation of %% (e.g. 200.1 %% 0.1 = 0.1 !!)
quot <- (stop_price - filters[filterType == 'PRICE_FILTER', minPrice]) / filters[filterType == 'PRICE_FILTER', tickSize]
stopifnot(abs(quot - round(quot)) < 1e-10)
}
params$stopPrice = stop_price
}
if (!missing(iceberg_qty)) {
if (iceberg_qty > 0) {
stopifnot(time_in_force == 'GTC')
stopifnot(ceiling(quantity / iceberg_qty) <= filters[filterType == 'ICEBERG_PARTS', limit])
stopifnot(iceberg_qty >= filters[filterType == 'LOT_SIZE', minQty],
iceberg_qty <= filters[filterType == 'LOT_SIZE', maxQty])
# work around the limitation of %% (e.g. 200.1 %% 0.1 = 0.1 !!)
quot <- (iceberg_qty - filters[filterType == 'LOT_SIZE', minQty]) / filters[filterType == 'LOT_SIZE', stepSize]
stopifnot(abs(quot - round(quot)) < 1e-10)
}
params$icebergQty = iceberg_qty
}
if (isTRUE(test)) {
message('TEST')
ord <- binance_query(endpoint = 'api/v3/order/test', method = 'POST', params = params, sign = TRUE)
if (is.list(ord) & length(ord) == 0) {
ord <- 'OK'
}
} else {
ord <- binance_query(endpoint = 'api/v3/order', method = 'POST', params = params, sign = TRUE)
ord$fills <- NULL
ord <- as.data.table(ord)
for (v in c('price', 'origQty', 'executedQty', 'cummulativeQuoteQty')) {
ord[, (v) := as.numeric(get(v))]
}
for (v in c('transactTime')) {
ord[, (v) := as.POSIXct(get(v)/1e3, origin = '1970-01-01')]
}
# return with snake_case column names
setnames(ord, to_snake_case(names(ord)))
}
data.table(ord)
}
formals(binance_new_order)$side <- BINANCE$SIDE
formals(binance_new_order)$type <- BINANCE$TYPE
formals(binance_new_order)$time_in_force <- BINANCE$TIMEINFORCE
#' Query order on the Binance account
#' @param symbol string
#' @param order_id optional number
#' @param client_order_id optional string
#' @return data.table
#' @export
#' @importFrom snakecase to_snake_case
#' @examples \dontrun{
#' binance_query_order('ARKETH')
#' binance_query_order('ARKBTC', client_order_id = 'myOrder7')
#' }
binance_query_order <- function(symbol, order_id, client_order_id) {
stopifnot(!missing(order_id) | !missing(client_order_id))
params <- list(symbol = symbol)
if (!missing(order_id)) {
params$orderId = order_id
}
if (!missing(client_order_id)) {
params$origClientOrderId = client_order_id
}
ord <- binance_query(endpoint = 'api/v3/order', method = 'GET', params = params, sign = TRUE)
ord <- as.data.table(ord)
# ncol(ord) == 2 is error message
if (nrow(ord) > 0 & ncol(ord) > 2) {
for (v in c('price', 'origQty', 'executedQty', 'cummulativeQuoteQty', 'stopPrice', 'icebergQty')) {
ord[, (v) := as.numeric(get(v))]
}
for (v in c('time', 'updateTime')) {
ord[, (v) := as.POSIXct(get(v)/1e3, origin = '1970-01-01')]
}
# return with snake_case column names
setnames(ord, to_snake_case(names(ord)))
}
data.table(ord)
}
#' Cancel order on the Binance account
#' @param symbol string
#' @param order_id optional number
#' @param client_order_id optional string
#' @return data.table
#' @export
#' @importFrom snakecase to_snake_case
#' @examples \dontrun{
#' binance_cancel_order('ARKETH', order_id = 123456)
#' binance_cancel_order('ARKBTC', client_order_id = 'myOrder7')
#' }
binance_cancel_order <- function(symbol, order_id, client_order_id) {
stopifnot(!missing(order_id) | !missing(client_order_id))
params <- list(symbol = symbol)
if (!missing(order_id)) {
params$orderId = order_id
}
if (!missing(client_order_id)) {
params$origClientOrderId = client_order_id
}
ord <- binance_query(endpoint = 'api/v3/order', method = 'DELETE', params = params, sign = TRUE)
ord <- as.data.table(ord)
# ncol(ord) == 2 is error message
if (nrow(ord) > 0 & ncol(ord) > 2) {
for (v in c('price', 'origQty', 'executedQty', 'cummulativeQuoteQty')) {
ord[, (v) := as.numeric(get(v))]
}
# return with snake_case column names
setnames(ord, to_snake_case(names(ord)))
}
data.table(ord)
}
#' Fetch open orders from the Binance account
#' @param symbol optional string
#' @return data.table
#' @export
#' @importFrom snakecase to_snake_case
#' @examples \dontrun{
#' binance_open_orders('ARKETH')
#' binance_open_orders() # all symbols - binance.weight 40
#' }
binance_open_orders <- function(symbol) {
if (!missing(symbol)) {
params <- list(symbol = symbol)
} else {
params <- list()
}
ord <- binance_query(endpoint = 'api/v3/openOrders', params = params, sign = TRUE)
if (is.null(names(ord))) {
ord <- rbindlist(ord)
} else {
ord <- as.data.table(ord)
}
if (nrow(ord) > 0) {
for (v in c('price', 'origQty', 'executedQty', 'cummulativeQuoteQty', 'stopPrice', 'icebergQty')) {
ord[, (v) := as.numeric(get(v))]