binance / binance-signature-examples Goto Github PK
View Code? Open in Web Editor NEWExamples of generating HMAC and RSA signature for Binance API
Examples of generating HMAC and RSA signature for Binance API
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 response
10.23.0
No response
Chrome
Linux
No response
No response
Originally posted by @seaona in MetaMask/metamask-extension#16743
c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71
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;
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
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.
I have a proposal. I have a dart class for signature creation and http calls example. Pull request are desabled? How can I contribute?
NodeJS "crypto" Package is Deprecated in favor of "crypto-js".
https://www.npmjs.com/package/crypto
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
In most of case, url is XXX?timestamp={{timestamp}}&signature={{signature}}
exemple :
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."}
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
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;
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(
}
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);
?>`
Please would you create another signature example like https://github.com/binance/binance-signature-examples/blob/master/python/futures/test_user_data_stream.py, which shows us how to stream the listen key data asynschronously such that we can listen to the ORDER_TRADE_UPDATE
messages?
Thanks
Gabriel
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;
}
}
);
}
Hello!
It would be greatly appreciated if someone could add an example for Java aswell.
Thank you!
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 = "{}×tamp={}".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.
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:
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.
Thank you so much for sharing the examples.
By comparing the python-binance package from https://github.com/sammchardy/python-binance/blob/master/binance/client.py, I find that using send_signed_request and send_public_request in the python example takes about 30% more time to run.
CPU consumption is also higher.
Do you know what could be the possible reasons?
Thanks in advance!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.