Python
1 import hmac
2 import hashlib
3 import json
4 import uuid
5 from datetime import datetime, timezone
6 from urllib.parse import quote
7 import base64
8
9 # Initialize Configuration and Parameters
10 optional_api_endpoint = "<api_endpoint>"
11 app_key = "<your_app_key>"
12 app_secret = "<your_app_secret>"
13
14 # Request URI
15 uri = '/trading/accounts/list'
16
17 # Signature Header
18 headers = {
19 'x-app-key': app_key,
20 'x-signature-algorithm': 'HMAC-SHA256',
21 'x-signature-version': '1.0',
22 'x-signature-nonce': uuid.uuid4().hex,
23 'x-timestamp': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
24 'host': optional_api_endpoint,
25 'Content-Type': 'application/json'
26 }
27
28 query_params = {
29 }
30
31 body_params = {
32 }
33
34
35 def generate_signature(uri, query_params, body_params, headers, app_secret):
36 query_params = query_params or {}
37 # Integrate signature parameters
38 params_dict = query_params.copy()
39 # The signature algorithm must match the hash function below and is refreshed in place
40 headers['x-signature-algorithm'] = 'HMAC-SHA256'
41 # Parameters in the Signature Header excluding the x-signature parameter.
42 params_dict.update({
43 'x-app-key': headers['x-app-key'],
44 'x-signature-algorithm': headers['x-signature-algorithm'],
45 'x-signature-version': headers['x-signature-version'],
46 'x-signature-nonce': headers['x-signature-nonce'],
47 'x-timestamp': headers['x-timestamp'],
48 'host': headers['host']
49 })
50
51 # Sort the dictionary from small to large according to the parameter's key
52 sorted_params = sorted(params_dict.items())
53 # Concatenate the sorted parameters into a string
54 param_string = '&'.join([f"{k}={v}" for k, v in sorted_params])
55
56 # Calculate the SHA256 of the request body (if any)
57 body_sha256 = ""
58 if body_params is not None:
59 body_json = json.dumps(body_params, ensure_ascii=False, separators=(',', ':'))
60 body_sha256 = hashlib.sha256(body_json.encode()).hexdigest().upper()
61
62 # Build the sign string
63 sign_string = f"{uri}&{param_string}{'&' + body_sha256 if body_sha256 else ''}"
64
65 # Encode Request Elements
66 encoded_sign_string = quote(sign_string, safe='')
67
68 # Generating Signature
69 # base64(HMAC-SHA256(Part 1 + "&", Part 2))
70 secret = f"{app_secret}&"
71 signature = hmac.new(
72 secret.encode(),
73 encoded_sign_string.encode(),
74 hashlib.sha256
75 ).digest()
76
77 sign_string = base64.b64encode(signature).decode('utf-8')
78 print(f"Signature: {sign_string}")
79 return sign_string
80