Reputation: 421
I have a code snippet I am trying to prove works and allows me to connect to the bitunix futures API. I have an idea for a bot I want to write.
Instructions for creating the signature: [https://openapidoc.bitunix.com/doc/common/sign.html]
Api I want to call: [https://openapidoc.bitunix.com/doc/account/get_single_account.html]
Here is the code I have written so far. I have a valid API key & secret (shown below as abc) but it continues to fail. I get the following error: I can reproduce this in the script as well as with Postman.
Response: {'code': 10007, 'data': None, 'msg': 'Signature Error'}
import requests
import hashlib
import uuid
import time
from urllib.parse import urlencode
def sha256_hex(input_string):
return hashlib.sha256(input_string.encode('utf-8')).hexdigest()
def generate_signature(api_key, secret_key, nonce, timestamp, query_params):
"""
Generate the double SHA-256 signature as per Bitunix API requirements.
"""
# Concatenate nonce, timestamp, api_key, query_params, and an empty body
digest_input = nonce + timestamp + api_key + query_params + ""
# First SHA-256 hash
digest = sha256_hex(digest_input)
# Append secret_key to the digest
sign_input = digest + secret_key
# Second SHA-256 hash
signature = sha256_hex(sign_input)
return signature
def get_account_info(api_key, secret_key, margin_coin):
"""
Call the Bitunix 'Get Single Account' endpoint with proper signing.
"""
# Generate nonce: 32-character random string
nonce = uuid.uuid4().hex
# Generate timestamp in YYYYMMDDHHMMSS format
timestamp = time.strftime("%Y%m%d%H%M%S", time.gmtime())
# Set query parameters
params = {"marginCoin": margin_coin}
query_string = urlencode(params)
# Generate the signature
signature = generate_signature(api_key, secret_key, nonce, timestamp, query_string)
headers = {
"api-key": api_key,
"sign": signature,
"timestamp": timestamp,
"nonce": nonce,
"Content-Type": "application/json"
}
base_url = "https://fapi.bitunix.com"
request_path = "/api/v1/futures/account"
url = f"{base_url}{request_path}?{query_string}"
print(f"Query String: {query_string}")
print(f"Digest Input: {nonce + timestamp + api_key + query_string + ''}") # Debugging digest input
print(f"Signature: {signature}")
print(f"URL: {url}")
response = requests.get(url, headers=headers)
return response.json()
# Example usage
if __name__ == "__main__":
api_key = "your_api_key" # Replace with your actual API key
secret_key = "your_secret_key" # Replace with your actual secret key
margin_coin = "USDT" # Example margin coin
result = get_account_info(api_key, secret_key, margin_coin)
print("Response:", result)
Upvotes: 0
Views: 31