Search code examples
rpostsha256hmac

R Binance API HMAC SHA256 signed message


I'm trying to send over signed API messages using the Binance APIs I keep failing with a 404 error. Can someone help me out with the below code please?

library(jsonlite)
library(httr)
library(dplyr)
library(digest)


timestamp <- 1516941586 #as.numeric(as.POSIXct(Sys.time()))

post_message <- paste0(timestamp, 'public.api' ) # data_client.id = client 
id # data_key = key

sha.message <- toupper(digest::hmac('private.api', object = post_message, 
algo = 'sha256', serialize = F))

url <- 'https://api.binance.com/api/v3/account'

body = list('timestamp' = timestamp, 'signature' = sha.message)
body2 <- paste("?timestamp=",timestamp,"&signature=",sha.message, sep = "")


httr::POST(url, body2 = body, verbose())

Here is the documentation https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md


Solution

  • Based on example under section "SIGNED Endpoint Examples for POST /api/v1/order" in the website, you can follow something similar. You will need to replace with your own apiKey and secretKey.

    library(httr)
    library(openssl)
    
    url <- 'https://api.binance.com/api/v3/account'
    apiKey <- "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A"
    secretKey <- "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"
    
    timestamp <- 1516941586
    recvWindow <- 1e20
    postmsg <- paste0("timestamp=", timestamp, "&recvWindow=", recvWindow)
    signature <- openssl::sha256(postmsg, key=secretKey)
    
    GET(url, 
        add_headers("X-MBX-APIKEY"=apiKey),
        query=list(timestamp=timestamp, recvWindow=recvWindow, signature=signature), 
        verbose())