Search code examples
curlbinance

How to authenticate a cURL request to the Binance API?


Trying to learn about crypto.

I would like to manually create an order to Binance.

I have the API key and secret, I can create requests to get the price and other info, but I am not sure how to authenticate requests to create an order.

Thanks.


Solution

  • You need to create a signature of your params (sign it using your private key) and then include the signature with the request (as well as rest of the params).

    The official docs have an example of creating the signature using openssl and then sending the request (containing the signature and other params) using curl.

    [linux]$ echo -n "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559" | openssl dgst -sha256 -hmac "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"
    (stdin)= c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71
    
    (HMAC SHA256)
    [linux]$ curl -H "X-MBX-APIKEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A" -X POST 'https://api.binance.com/api/v3/order' -d 'symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559&signature=c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71'
    

    For a JS implementation, see for example source of the binance-api-node NPM package. It uses the native crypto package and its createHmac() method.

    const signature = crypto
      .createHmac('sha256', apiSecret)
      .update(makeQueryString({ ...data, timestamp }).substr(1))
      .digest('hex')