Hello. I am trying to make a market order for BTC with the API. Here is my code:
import requests
import hmac
import hashlib
import time
import base64
import json
timestamp = str(int(time.time()))
endpoint = "https://api.coinbase.com/api/v3/brokerage/orders"
payload = json.dumps({
"product_id": "BTC-USD",
"side": "BUY",
"order_configuration": {
"market_market_ioc": {
"quote_size": "5"
}
}
})
message = timestamp + 'POST' + endpoint + payload
signature = hmac.new(API_SEC.encode('utf-8'), message.encode('utf-8'), digestmod=hashlib.sha256).digest()
# signature = base64.b64encode(signature).decode()
headers = {
'Content-Type': 'application/json',
'CB-ACCESS-KEY': API,
'CB-ACCESS-SIGN': signature,
'CB-ACCESS-TIMESTAMP': timestamp
}
response = requests.post(endpoint, json=payload, headers=headers)
print(response.status_code)
print(response.content)
print(response.headers)
If I run the current code, this is my result:
400
b’400 Bad Request: invalid header value’
{‘Date’: ‘Tue, 24 Jan 2023 07:53:25 GMT’, ‘Content-Type’: ‘text/plain; charset=utf-8’, ‘Transfer-Encoding’: ‘chunked’, ‘Connection’: ‘keep-alive’, ‘CF-Cache-Status’: ‘DYNAMIC’, ‘Set-Cookie’: ‘__cf_bm=_GGIW62ebBAu939VVwicyWT0M_8sPfoghaXk3r5uYUs-1674546805-0-AdndUKReGTXdTQ7qbIwRjJZaMOaBRYg4biNvTfaoaDckcbdKmt2Zt6sY1pgF7hkHnM+HqjMRC+95EoK4DopbVCY=; path=/; expires=Tue, 24-Jan-23 08:23:25 GMT; domain=.coinbase.com; HttpOnly; Secure; SameSite=None’, ‘Strict-Transport-Security’: ‘max-age=31536000; includeSubDomains; preload’, ‘X-Content-Type-Options’: ‘nosniff’, ‘Server’: ‘cloudflare’, ‘CF-RAY’: ‘78e731fff890db59-LAX’}
If I comment out the second signature line I get this:
401
b’Unauthorized\n’
{‘Date’: ‘Tue, 24 Jan 2023 07:54:22 GMT’, ‘Content-Type’: ‘text/plain; charset=utf-8’, ‘Content-Length’: ‘13’, ‘Connection’: ‘keep-alive’, ‘Trace-Id’: ‘7219881873981354341’, ‘X-Content-Type-Options’: ‘nosniff’, ‘CF-Cache-Status’: ‘DYNAMIC’, ‘Set-Cookie’: ‘__cf_bm=n1NNwweGqk1Ab6CIs53v3v0SN6fhG162JNc4jxHQQPc-1674546862-0-AQ4+fdboYy8HN2tPIyUsnXQ8sIqHJJEAzYwX8gS8enZ3n3Iiay8nuX8q9Zr9uS+si/voIN/+gA4+SoQFychDOyo=; path=/; expires=Tue, 24-Jan-23 08:24:22 GMT; domain=.coinbase.com; HttpOnly; Secure; SameSite=None’, ‘Strict-Transport-Security’: ‘max-age=31536000; includeSubDomains; preload’, ‘Server’: ‘cloudflare’, ‘CF-RAY’: ‘78e733600b092ec6-LAX’}
Any help will be much appreciated! Thank you!