如何正确访问Coinbase高级API

huangapple go评论120阅读模式
英文:

how do i properly access the coinbase advanced api

问题

我正在尝试访问Coinbase高级API,但我遇到了这个错误:

  1. Traceback (most recent call last):
  2. File "D:\user\coinbase_neural_network.py", line 47, in collect_data
  3. candles = api.API.get_product_candles(product_id, start, end, granularity)
  4. File "D:\user\Coinbase_neural_network\api.py", line 76, in get_product_candles
  5. response.raise_for_status()
  6. File "C:\Users\micha\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 1021, in raise_for_status
  7. raise HTTPError(http_error_msg, response=self)
  8. requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api.coinbase.com/api/v3/brokerage/products/LTC-USD/candles?start=01-01-2021&end=01-01-2022&granularity=ONE_HOUR

当我尝试在这个类中使用collect_data函数时:

  1. import configparser
  2. import http.client
  3. import json
  4. import hashlib
  5. import hmac
  6. import time
  7. from typing import Tuple, List, Dict, Any
  8. import requests
  9. class API:
  10. config = configparser.ConfigParser()
  11. config.read(r"D:\user\config.ini")
  12. api_key = config.get('coinbase', 'API_KEY')
  13. secret_key = config.get('coinbase', 'SECRET_KEY')
  14. @staticmethod
  15. def generate_signature(timestamp: str, method: str, request_path: str, body: str) -> str:
  16. # 签名生成的部分代码
  17. @staticmethod
  18. def get_best_bid_ask() -> str:
  19. # 获取最佳买卖价的部分代码
  20. # 其他方法的定义...

一切都正常通过,这是时间戳:1690483742,以及URL:在收集数据时发生错误:400 Client Error: Bad Request for url: https://api.coinbase.com/api/v3/brokerage/products/LTC-USD/candles?start=01-01-2021&end=01-01-2022&granularity=ONE_HOUR

我输入日期有问题吗?

英文:

im trying to access the coinbase adveanced api ut im getting this error:
Traceback (most recent call last):
File "D:\user\coinbase_neural_network.py", line 47, in collect_data
candles = api.API.get_product_candles(product_id, start, end, granularity)
File "D:\user\Coinbase_neural_network\api.py", line 76, in get_product_candles
response.raise_for_status()
File "C:\Users\micha\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api.coinbase.com/api/v3/brokerage/products/LTC-USD/candles?start=01-01-2021&end=01-01-2022&granularity=ONE_HOUR

when i try to use the collect data function in this class:
import configparser
import http.client
import json
import hashlib
import hmac
import time
from typing import Tuple, List, Dict, Any
import requests

  1. class API:
  2. config = configparser.ConfigParser()
  3. config.read(r"D:\user\config.ini")
  4. api_key = config.get('coinbase', 'API_KEY')
  5. secret_key = config.get('coinbase', 'SECRET_KEY')
  6. @staticmethod
  7. def generate_signature(timestamp: str, method: str, request_path: str, body: str) -> str:
  8. signature_string = timestamp + method.upper() + request_path + body
  9. hmac_object = hmac.new(API.secret_key.encode(), signature_string.encode(), hashlib.sha256)
  10. return hmac_object.hexdigest()
  11. @staticmethod
  12. def get_best_bid_ask() -> str:
  13. payload: str = ''
  14. timestamp = str(int(time.time()))
  15. headers: dict[str, str] = {
  16. 'Content-Type': 'application/json',
  17. 'CB-ACCESS-KEY': API.api_key,
  18. 'CB-ACCESS-SIGN': API.generate_signature(timestamp, "GET", "/api/v3/brokerage/best_bid_ask", payload),
  19. 'CB-ACCESS-TIMESTAMP': timestamp,
  20. }
  21. with http.client.HTTPSConnection("api.coinbase.com") as conn:
  22. conn.request("GET", "/api/v3/brokerage/best_bid_ask", payload, headers)
  23. res: http.client.HTTPResponse = conn.getresponse()
  24. data: bytes = res.read()
  25. return data.decode("utf-8")
  26. @staticmethod
  27. def get_brokerage_accounts(limit: int, cursor: str) -> str:
  28. payload: str = ''
  29. timestamp = str(int(time.time()))
  30. headers: dict[str, str] = {
  31. 'Content-Type': 'application/json',
  32. 'CB-ACCESS-KEY': API.api_key,
  33. 'CB-ACCESS-SIGN': API.generate_signature(timestamp, "GET", f"/api/v3/brokerage/accounts?limit={limit}&cursor={cursor}", payload),
  34. 'CB-ACCESS-TIMESTAMP': timestamp,
  35. }
  36. with http.client.HTTPSConnection("api.coinbase.com") as conn:
  37. conn.request("GET", f"/api/v3/brokerage/accounts?limit={limit}&cursor={cursor}", payload, headers)
  38. res: http.client.HTTPResponse = conn.getresponse()
  39. data: bytes = res.read()
  40. return data.decode("utf-8")
  41. @staticmethod
  42. def get_product_candles(product_id: str, start: str, end: str, granularity: str) -> List[Dict[str, str]]:
  43. payload: str = ''
  44. timestamp = str(int(time.time()))
  45. headers: dict[str, str] = {
  46. 'Content-Type': 'application/json',
  47. 'CB-ACCESS-KEY': API.api_key,
  48. 'CB-ACCESS-SIGN': API.generate_signature(timestamp, "GET",
  49. f"/api/v3/brokerage/products/{product_id}/candles", payload),
  50. 'CB-ACCESS-TIMESTAMP': timestamp}
  51. start = start.replace(' ', 'T')
  52. end = end.replace(' ', 'T')
  53. url = f"https://api.coinbase.com/api/v3/brokerage/products/{product_id}/candles"
  54. params = {
  55. "start": start,
  56. "end": end,
  57. "granularity": granularity}
  58. print(timestamp)
  59. response = requests.get(url, params=params, headers=headers)
  60. response.raise_for_status()
  61. candles = response.json()
  62. return [dict(zip(["start", "low", "high", "open", "close", "volume"], c)) for c in candles]
  63. @staticmethod
  64. def get_market_trades(product_id: str, limit: int) -> Tuple[List[Dict[str, str]], str, str]:
  65. payload: str = ''
  66. timestamp = str(int(time.time()))
  67. headers: dict[str, str] = {
  68. 'Content-Type': 'application/json',
  69. 'CB-ACCESS-KEY': API.api_key,
  70. 'CB-ACCESS-SIGN': API.generate_signature(timestamp, "GET", f"/api/v3/brokerage/products/{product_id}/ticker?limit={limit}", payload),
  71. 'CB-ACCESS-TIMESTAMP': timestamp,
  72. }
  73. with http.client.HTTPSConnection("api.coinbase.com") as conn:
  74. conn.request("GET", f"/api/v3/brokerage/products/{product_id}/ticker?limit={limit}", payload, headers)
  75. res: http.client.HTTPResponse = conn.getresponse()
  76. data: bytes = res.read()
  77. trades: Dict[str, Any] = json.loads(data.decode("utf-8"))
  78. trade_data: List[Dict[str, str]] = [dict(zip(["trade_id", "product_id", "price", "size", "time", "side", "bid",
  79. "ask"], t)) for t in trades["trades"]]
  80. best_bid: str = trades["best_bid"]
  81. best_ask: str = trades["best_ask"]
  82. return trade_data, best_bid, best_ask
  83. @staticmethod
  84. def create_buy_market_order(client_order_id: str, product_id: str, side: str, order_configuration: str) -> str:
  85. payload: str = json.dumps({
  86. "client_order_id": client_order_id,
  87. "product_id": product_id,
  88. "side": side,
  89. "order_configuration": order_configuration
  90. })
  91. timestamp = str(int(time.time()))
  92. headers: dict[str, str] = {
  93. 'Content-Type': 'application/json',
  94. 'CB-ACCESS-KEY': API.api_key,
  95. 'CB-ACCESS-SIGN': API.generate_signature(timestamp, "POST", "/api/v3/brokerage/orders", payload),
  96. 'CB-ACCESS-TIMESTAMP': timestamp,
  97. }
  98. with http.client.HTTPSConnection("api.coinbase.com") as conn:
  99. conn.request("POST", "/api/v3/brokerage/orders", payload, headers)
  100. res: http.client.HTTPResponse = conn.getresponse()
  101. data: bytes = res.read()
  102. return data.decode("utf-8")
  103. @staticmethod
  104. def create_sell_market_order(client_order_id: str, product_id: str, side: str, order_configuration: str) -> str:
  105. payload: str = json.dumps({
  106. "client_order_id": client_order_id,
  107. "product_id": product_id,
  108. "side": side,
  109. "order_configuration": order_configuration
  110. })
  111. timestamp = str(int(time.time()))
  112. headers: dict[str, str] = {
  113. 'Content-Type': 'application/json',
  114. 'CB-ACCESS-KEY': API.api_key,
  115. 'CB-ACCESS-SIGN': API.generate_signature(timestamp, "POST", "/api/v3/brokerage/orders", payload),
  116. 'CB-ACCESS-TIMESTAMP': timestamp,
  117. }
  118. with http.client.HTTPSConnection("api.coinbase.com") as conn:
  119. conn.request("POST", "/api/v3/brokerage/orders", payload, headers)
  120. res: http.client.HTTPResponse = conn.getresponse()
  121. data: bytes = res.read()
  122. return data.decode("utf-8")

everything is passed right this is the timestamp: 1690483742
and url: Error occurred while collecting data: 400 Client Error: Bad Request for url: https://api.coinbase.com/api/v3/brokerage/products/LTC-USD/candles?start=01-01-2021&end=01-01-2022&granularity=ONE_HOUR
am i entering the date wrong?your text

答案1

得分: 0

你需要将时间发送为Unix时间戳。因此,请将此部分替换为:

  1. start = int(datetime.datetime.strptime(start, '%m-%d-%Y').timestamp())
  2. end = int(datetime.datetime.strptime(end, '%m-%d-%Y').timestamp())

假设(1)你在顶部导入了import datetime,并且(2)你始终以MM-DD-YYYY格式提供日期。

英文:

You need to send the times as Unix timestamps. So replace this:

  1. start = start.replace(' ', 'T')
  2. end = end.replace(' ', 'T')

With this:

  1. start = int(datetime.datetime.strptime(start, '%m-%d-%Y').timestamp())
  2. end = int(datetime.datetime.strptime(end, '%m-%d-%Y').timestamp())

That assumes (1) you have import datetime at the top, and (2) you always give your dates in MM-DD-YYYY format.

huangapple
  • 本文由 发表于 2023年7月28日 03:08:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定