Coder Social home page Coder Social logo

binance / binance-signature-examples Goto Github PK

View Code? Open in Web Editor NEW
226.0 226.0 87.0 51 KB

Examples of generating HMAC and RSA signature for Binance API

Python 41.17% JavaScript 1.30% PHP 5.26% Ruby 1.14% Shell 2.29% Makefile 0.61% C++ 9.59% Java 12.56% Perl 0.97% C# 23.63% Go 1.47%
api binance crypto exchange hashing signature

binance-signature-examples's People

Contributors

2pd avatar aisling-2 avatar chairz avatar ishuen avatar jonte-z avatar tantialex 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  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

binance-signature-examples's Issues

### Describe the bug

Describe the bug

Problem: a Dapp can trigger a Token Transfer for a Token which I have 0 balance. This results in paying tx fees for an already failed transaction. We could know beforehand that the transaction was going to fail if we checked against our token balance.

Notice this behaviour is not possible from MetaMask itself, as before landing to the Confirmation screen, there is a validation that checks our Token balance is greater than the Amount for that Send.

no-token-balance-send.mp4

Steps to reproduce

  1. Go to Test Dapp https://metamask.github.io/test-dapp/
  2. Connect to Test Dapp
  3. Click Create Contract and Accept Tx on MM
  4. Click Add Token to Wallet and Accept on MM
  5. Go to MM and send all the Tokens to another address
  6. Go back to Testdapp
  7. Click Transfer Tokens -- see that you can proceed with this transaction, which will result in a failed tx as you don't have balance for that token

Error messages or log output

No response

Version

10.23.0

Build type

No response

Browser

Chrome

Operating system

Linux

Hardware wallet

No response

Additional context

No response

Originally posted by @seaona in MetaMask/metamask-extension#16743

?

c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71

Binance API, Get Balance, Delphi

Hi, I use following code to get balances from my SPOT account on Binance. But after execution, I allways get 400 Bad request message.

  Form1.RESTClient1.BaseURL := 'https://api.binance.com/api/v3/account';
  Form1.RESTRequest1.Params.Clear;
  Form1.RESTRequest1.METHOD := rmGet;

  aParam := Form1.RESTRequest1.Params.AddItem;
  aParam.ContentType:=ctapplication_x_www_form_urlencoded;
  aParam.Kind := pkHTTPHEADER;
  aParam.name := 'X-MBX-APIKEY';
  aParam.Value := Form1.APIKEY_Binance;

  TimeStamp := Form1.UNIXTimeInMilliseconds;
  aParam := Form1.RESTRequest1.Params.AddItem;
  aParam.ContentType:=ctapplication_x_www_form_urlencoded;
  aParam.Kind := pkGETorPOST; 
  aParam.name := 'timestamp';
  aParam.Value := TimeStamp;


  PRE_SIGN := format('%s?timestamp=%s', [Form1.RESTClient1.BaseURL,
    TimeStamp]);
  SIGNATURE := SHA512DigestToHexW(CalcHMAC_SHA512(Form1.SECRET_Binance,
    PRE_SIGN));
  aParam := Form1.RESTRequest1.Params.AddItem;
  aParam.ContentType:=ctapplication_x_www_form_urlencoded;
  aParam.Kind := pkHTTPHEADER;
  aParam.name := 'signature';
  aParam.Value := SIGNATURE;

  Form1.RESTRequest1.Execute;

exchangeInfo API not working

Hello, I have tried on other endpoint than in examples, but I cannot get it working. (other examples work)
The endpoint I am testing is "GET /sapi/v1/convert/exchangeInfo" from documentation at https://binance-docs.github.io/apidocs/spot/en/#convert-endpoints

My code that does not work is
params = {"fromAsset":"BTC"}
response = send_public_request("/sapi/v1/convert/exchangeInfo", params)
print(response)

Can you please help me to format the request correctly? Thank you very much, Jan

APIError(code=-1022): Signature for this request is not valid.

I have a Binance Future Order that is throwing the below error:

APIError(code=-1022): Signature for this request is not valid.

My code for the order is as below:

client.futures_create_order(
symbol='ADAUSDT',
side=Side,
type='MARKET',
quantity=trade_quantity,
recvWindow=5000)
I can retrieve prices & a/c info with the Binance API keys but when I put the future order as above it throws an error for invalid signature. I saw solutions for this error but could not understand how to add to above order & place it.

I am not a IT person & have learned python just by google search in last week. Any help on adding the signature to the code will be appreciated, thanks a lot.

Change proposal

I have a proposal. I have a dart class for signature creation and http calls example. Pull request are desabled? How can I contribute?

Error with /fapi/v1/order - Python

Hi

I use your code (https://github.com/binance-exchange/binance-signature-examples/blob/master/python/delivery-futures.py) and I ave 2 errors when I want to use /fapi/v1/order

1. Char ? or &

In most of case, url is XXX?timestamp={{timestamp}}&signature={{signature}}
exemple :

  • /fapi/v2/positionRisk?timestamp={{timestamp}}&signature={{signature}}
  • /fapi/v2/account?timestamp={{timestamp}}&signature={{signature}}

So in your code, the "?timestamp" is hard code :
url = BASE_URL + url_path + '?' + query_string + '&signature=' + hashing(query_string)

But to use API for New Order, we must use :
/fapi/v1/order?symbol=LTCUSDT&side=BUY&positionSide=BOTH&type=MARKET&quantity=0.087 & timestamp={{timestamp}}&signature={{signature}}

So it's an issue
With this URL : https://fapi.binance.com/fapi/v1/order?symbol=LTCUSDT&side=SELL&positionSide=BOTH&type=MARKET&quantity=0.087?timestamp=1620474622959&signature=7ba203ec45bfa9c6e70a80cd8a482fa85822c5384243047d0c84c34f79cbc...
I have this error message :
{'code': -1102, 'msg': "Mandatory parameter 'timestamp' was not sent, was empty/null, or malformed."}

2. Error with signature to past order

I tested to change code to avoid issue with this :

def send_signed_request(http_method, url_path, payload={},defaultItemTimestamp='?'):
    query_string = urlencode(payload)
    query_string = query_string.replace('%27', '%22')

    if query_string:
        query_string = "{}"+defaultItemTimestamp+"timestamp={}".format(query_string, get_timestamp())
    else:
        query_string = 'timestamp={}'.format(get_timestamp())

    url = BASE_URL + url_path + defaultItemTimestamp + query_string + '&signature=' + hashing(query_string)
    print(url)
    params = {'url': url, 'params': {}}
    response = dispatch_request(http_method)(**params)
    return response.json()

But now I have this error :
URL : https://fapi.binance.com/fapi/v1/order?symbol=LTCUSDT&side=SELL&positionSide=BOTH&type=MARKET&quantity=0.087?timestamp=1620474622959&signature=7ba203ec45bfa9c6e70a80cd8a482fa85822c5384243047d0c84c34f79c.....
Error message : {'code': -1102, 'msg': "Mandatory parameter 'timestamp' was not sent, was empty/null, or malformed."}

Could you reproduce the probleme et correct its ?

Best regards

future

hi
how can i use this for future https://testnet.binancefuture.com

I have two days to try, but I still can not

my code
`<?php

$KEY= 'xx';
$SECRET = 'xx';

// $BASE_URL = 'https://api.binance.com/'; // production
$BASE_URL = 'https://testnet.binancefuture.com/'; // testnet

function signature($query_string, $secret) {
return hash_hmac('sha256', $query_string, $secret);
}

function sendRequest($method, $path) {
global $KEY;
global $BASE_URL;

$url = "${BASE_URL}${path}";

echo "requested URL: ". PHP_EOL;
echo $url. PHP_EOL;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-MBX-APIKEY:'.$KEY));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, $method == "POST" ? true : false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$execResult = curl_exec($ch);
$response = curl_getinfo($ch);

// if you wish to print the response headers
// echo print_r($response);

curl_close ($ch);
return json_decode($execResult, true);
}

function signedRequest($method, $path, $parameters = []) {
global $SECRET;

$parameters['timestamp'] = round(microtime(true) * 1000);
$query = buildQuery($parameters);
$signature = signature($query, $SECRET);
return sendRequest($method, "${path}?${query}&signature=${signature}");
}

function buildQuery(array $params)
{
$query_array = array();
foreach ($params as $key => $value) {
if (is_array($value)) {
$query_array = array_merge($query_array, array_map(function ($v) use ($key) {
return urlencode($key) . '=' . urlencode($v);
}, $value));
} else {
$query_array[] = urlencode($key) . '=' . urlencode($value);
}
}
return implode('&', $query_array);
}

// get orderbook
// $response = sendRequest('GET', 'api/v3/depth?symbol=BNBUSDT&limit=5');
// echo json_encode($response);

// get account information, make sure API key and secret are set
// $response = signedRequest('GET', 'api/v3/account');
// echo json_encode($response);

// place order, make sure API key and secret are set, recommend to test on testnet.
$response = signedRequest('POST', 'fapi/v1/order', [
'symbol' => 'ETHUSDT',
'side' => 'BUY',
'type' => 'LIMIT',
'timeInForce' => 'GTC',
'quantity' => 1,
'price' => 3000,

// 'newClientOrderId' => 'my_order', // optional
'newOrderRespType' => 'FULL' //optional
]);
echo '

' , json_encode($response);

?>`

nodejs example

I think it would be nice to mention that for all this to work you need a header with your key in the request.
Of course you can easily figure this out in the docs, but would be nice to have in here to make it compact.

Here is some crappy code from me, don't hesitate to scrap a cleaner example from it :)

function getAccountInfo() {

    let timestamp = Date.now();
    let query = `timestamp=${timestamp}`;
    let signature = createSignature(query);

    console.log(query, signature, `${binance_endpoint}/api/v3/account?${query}&signature=${signature}`)

    request.get({
        url: `${binance_endpoint}/api/v3/account?${query}&signature=${signature}`,
        headers: {
            "X-MBX-APIKEY": env.BINANCE.KEY,
        }}, function (error, response, body) {
            if (!error && response) {
                if (response.statusCode == 200) {

                    let data = JSON.parse(body);

                    console.log(data);
                    

                } else {

                    // api rate limit exceeded
                    if (response.statusCode == 429) {
                        throw("Api limit breached");
                    }

                    console.error('bad status code', response.statusCode);
                    return;
                }
            } else {
                console.log('error', error);
                console.log('response.statusCode', response.statusCode);
                return;
            }
        }
    );

}

Java example

Hello!

It would be greatly appreciated if someone could add an example for Java aswell.

Thank you!

Order market buy and sell not shown on binance transaction history on SPOT Balance.

Hello Everyone

I m trying to use you this python binance to buy and sell crypto currency.

Currently i have more than enough balance to place BTCUSDT trade of buy or sell in my account. I have written a simple script to buy crypto first and then after some delay time sell them using your following code :

Code used :

import hmac
import time
import hashlib
import requests
from urllib.parse import urlencode
KEY = '4aoQqPmQKUt8KLyr2BI4XFl8JdiyNN2w7RBkuk9VenqS3CCx96FXJUg93sb6H1Oa'
SECRET = 'FgxGtBtVk4P9goXs0G9k8syBSQNoXyHXKX8tvG7mMAJLKwZ5ZinZMHl64S86iHKT'
BASE_URL = 'https://api.binance.com' # production base url
# BASE_URL = 'https://testnet.binance.vision' # testnet base url

''' ======  begin of functions, you don't need to touch ====== '''
def hashing(query_string):
    return hmac.new(SECRET.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()

def get_timestamp():
    return int(time.time() * 1000)


def dispatch_request(http_method):
    session = requests.Session()
    session.headers.update({
        'Content-Type': 'application/json;charset=utf-8',
        'X-MBX-APIKEY': KEY
    })
    return {
        'GET': session.get,
        'DELETE': session.delete,
        'PUT': session.put,
        'POST': session.post,
    }.get(http_method, 'GET')

# used for sending request requires the signature
def send_signed_request(http_method, url_path, payload={}):
    query_string = urlencode(payload, True)
    if query_string:
        query_string = "{}&timestamp={}".format(query_string, get_timestamp())
    else:
        query_string = 'timestamp={}'.format(get_timestamp())

    url = BASE_URL + url_path + '?' + query_string + '&signature=' + hashing(query_string)
    print("{} {}".format(http_method, url))
    params = {'url': url, 'params': {}}
    response = dispatch_request(http_method)(**params)
    return response.json()

# used for sending public data request
def send_public_request(url_path, payload={}):
    query_string = urlencode(payload, True)
    url = BASE_URL + url_path
    if query_string:
        url = url + '?' + query_string
    print("{}".format(url))
    response = dispatch_request('GET')(url=url)
    return response.json()

''' ======  end of functions ====== '''

### public data endpoint, call send_public_request #####
# get klines
response = send_public_request('/api/v3/klines' , {"symbol": "BTCUSDT", "interval": "5m"})
##print(response)


### USER_DATA endpoints, call send_signed_request #####
# get account informtion
# if you can see the account details, then the API key/secret is correct
response = send_signed_request('GET', '/api/v3/account')
##print(response)


# # place an order
# if you see order response, then the parameters setting is correct
params = {
    "symbol": "BTCUSDT",
    "side": "SELL",
    "type": "MARKET",
    "quantity": '0.0015'
}
response = send_signed_request('POST', '/api/v3/order', params)
print(response)

In the terminal i see no errors, buy and sell are successful i even get order id, trade id etc but when i check the history in SPOT order of trade history it doesn't appear in there.

Terminal Window screenshot attached. But in the SPOT wallet order history or trade history it doesn't shows up. Only those trades are shown that I did manually.
ceb3fcc7-07f6-41ab-8287-a12cd90e6620

Error -2008, Invalid Api-Key ID. My API key is correct

While trying to request anything that needs a signature i get this "{'code': -2008, 'msg': 'Invalid Api-Key ID.'}" or this "{"code": -2015, "msg": "Invalid API-key, IP, or permissions for action."}" error. When i request public info i do not get any errors. I know that my api key is correct because i have trouble shot it, along with the IP whitelisting feature. The api key is being used with a different wrapper with no api key errors (not at the same time).

Here is my code:

bintest1.txt

This returns:
(all correct klines)
{"code": -2015, "msg": "Invalid API-key, IP, or permissions for action."}
{'code': -2008, 'msg': 'Invalid Api-Key ID.'}

Again, i know my keys are correct because i used the same ones in a different script with success. Thanks for any help in advance.

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.