使用python3的Coinbase高级交易API连接不起作用

3htmauhk  于 2023-01-10  发布在  Python
关注(0)|答案(1)|浏览(127)

我尝试了以下基于Coinbase文档coinbase doc的代码。文档是为Python2提供的,但我已经修改并将其用于Python3,因为我正在尝试连接到Coinbase Coinbase Advanced trade doc中的高级交易API

import datetime
import time
import hmac
import hashlib
import http.client

secret_key='***'    #hidden
api_key='***'       #hidden

date_time = datetime.datetime.utcnow()
timestamp=int(time.mktime(date_time.timetuple())) # timestamp should be from UTC time and no decimal allowed

method = "GET" # method can be GET or POST. Only capital is allowed
request_path = 'api/v3/brokerage/accounts'
body=''
message= str(timestamp) + method + request_path + body
signature = hmac.new(secret_key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest()

headers={
'accept':'application/json',
'CB-ACCESS-KEY': api_key,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-SIGN': signature
}

conn = http.client.HTTPSConnection("api.coinbase.com")
payload = ''

conn.request("GET", "/api/v3/brokerage/accounts", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

执行此代码时,我希望帐户详细信息。但我得到未经授权的错误和错误代码401作为API返回。
我早些时候能够连接到Coinbase Pro API,一切都很好,直到Coinbase和Coinbase Pro合并。现在无法弄清楚如何连接到Coinbase中的高级交易功能。

vi4fp9gy

vi4fp9gy1#

好的,我做了两个更新来运行它。
1.在request_path = '/api/v3/brokerage/accounts'中的api之前插入一个/:)
1.将生成timestamp的方式更改为timestamp = str(int(time.time()))
我以为把你的timestamp更新为字符串就能解决这个问题,但是没有,所以我恢复了我生成它的方式。也许有人能告诉我们为什么一个能用,一个不能用。如果我弄清楚了,我一定会更新这篇文章。
这是完整的代码。我保持其他一切不变,但用我的注解替换了你的注解。

import datetime
import time
import hmac
import hashlib
import http.client

secret_key = '***'  
api_key = '***'  

# This is the first part where you were getting time
#date_time = datetime.datetime.utcnow() 

# And this is the second part where you format it as an integer
#timestamp=int(time.mktime(date_time.timetuple())) 

# I cast your timestamp as a string, but it still doesn't work, and I'm having a hard time figuring out why.
#timestamp=str(int(time.mktime(date_time.timetuple()))) 

# So I reverted to the way that I'm getting the timestamp, and it works
timestamp = str(int(time.time()))

method = "GET"
request_path = '/api/v3/brokerage/accounts' # Added a forward slash before 'api'
body=''
message= str(timestamp) + method + request_path + body
signature = hmac.new(secret_key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest()

headers={
'accept':'application/json',
'CB-ACCESS-KEY': api_key,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-SIGN': signature
}

conn = http.client.HTTPSConnection("api.coinbase.com")
payload = ''

conn.request("GET", "/api/v3/brokerage/accounts", payload, headers)
# You were probably troubleshooting, but the above line is redundant and can be simplified to:
# conn.request("GET", request_path, body, headers) 

res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

相关问题