
Python調(diào)用Google Bard API 完整指南
是也不是。這兩個平臺均歸 Coinbase Global Inc 所有,但 Coinbase 更像是您的虛擬錢包,而 Coinbase Pro 則適合交易高級且準備與其他用戶交易的人。
我們可以有力地論證說,Coinbase Pro API 比普通的 Coinbase API 更好,因為它允許更多高級功能和端點。
Coinbase Pro API 可在 100 多個國家/地區(qū)使用,完整列表可在此處找到。為了方便您,我在下圖中匯總了所有獲準的國家/地區(qū):
Coinbase Pro API 可以替換為其他更適合您需求的交易所。以下是其中一些:
Coinbase Pro API 的可用和維護的客戶端如下:
有兩種方法可以開始使用 Coinbase Pro。第一種方法是直接在 Coinbase Pro 登錄頁面上創(chuàng)建一個帳戶,第二種方法是將其與已創(chuàng)建的 Coinbase 帳戶集成。
讓我們先從后者開始。轉(zhuǎn)到以下鏈接上的 Coinbase Pro 頁面:Coinbase Pro | 數(shù)字資產(chǎn)交易所
到達那里后,點擊右上角的藍色“開始”按鈕。然后,您需要指定您的基本帳戶詳細信息并驗證您的電子郵件地址并通過電話進行身份驗證。
根據(jù)您所在的地區(qū),您將被要求提供您的姓名、出生日期、地址、意圖、資金來源、職業(yè)和雇主。您還應(yīng)該準備好您的身份證件,因為您將被要求提供身份證件的照片。
身份驗證后,系統(tǒng)會要求您關(guān)聯(lián)銀行賬戶。您可以跳過此步驟,稍后再選擇“開始交易”選項返回。第一種方法就是這樣。
第二種方式是使用您的 Coinbase 帳戶憑證登錄,這將自動鏈接兩者并允許在它們之間轉(zhuǎn)移資金。
如果您想選擇第二種選擇,但沒有 Coinbase 帳戶,您可以查看我們的Coinbase 文章入門部分。
現(xiàn)在點擊右上角的賬戶圖標和 API,然后點擊“+ 新 API 密鑰”按鈕。然后您將指定 API 密鑰權(quán)限、昵稱和密碼。
之后,您可以創(chuàng)建 API 密鑰。系統(tǒng)將提示您輸入驗證碼,完成后將顯示應(yīng)安全存儲的密鑰。
現(xiàn)在我們的 API 密鑰已創(chuàng)建并可運行,我們可以通過檢查最常用的公共和私有端點來測試其功能。請務(wù)必使用以下命令安裝 Python 客戶端:
pip install cbpro
可以使用get_products
帶有 Coinbase Pro API python 庫的端點獲取交易對。
現(xiàn)在,讓我們導(dǎo)入庫,初始化客戶端,獲取我們的產(chǎn)品數(shù)據(jù),并將其放入 pandas 數(shù)據(jù)框中以便更好地觀察:
import cbpro
import pandas as pd
c = cbpro.PublicClient()
data = pd.DataFrame(c.get_products())
data.tail().T
這是相當(dāng)可觀的交易對數(shù)量,但還可以更多。
可以使用 Coinbase Pro API 的get_product_ticker
端點獲取價格數(shù)據(jù)。您需要指定要獲取數(shù)據(jù)的股票代碼參數(shù)。
讓我們獲取 Cardano 資產(chǎn)的數(shù)據(jù):
ticker = c.get_product_ticker(product_id='ADA-USD')
ticker
{'trade_id': 15598647,
'price': '1.7446',
'size': '27.35',
'time': '2021-05-26T18:24:17.9723252',
'bid': '1.7435',
'ask': '1.7444',
'volume': '223045485.25'}
您還可以使用Coinbase Pro REST API端點通過以下方式獲取數(shù)據(jù):
import requests
ticker = requests.get('https://api.pro.coinbase.com/products/ADA-USD/ticker').json()
ticker
{'trade_id': 16369597,
'price': '1.6106',
'size': '1012.91',
'time': '2021-05-30T08:39:31.8363332',
'bid': '1.6106',
'ask': '1.6111',
'volume': '197711129.46'}
可以使用 Coinbase Pro API 的 get_product_historic_rates 端點獲取歷史數(shù)據(jù)。您可以將粒度、開始和結(jié)束日期指定為 API 請求的參數(shù)。
讓我們使用默認參數(shù)獲取 ETH-USD 的歷史數(shù)據(jù),并將其排列到已清理的 pandas 數(shù)據(jù)框中。我們將重命名列,將 Unix 時間轉(zhuǎn)換為標準時間,并按此對數(shù)據(jù)進行排序。
historical = pd.DataFrame(c.get_product_historic_rates(product_id='ETH-USD'))
historical.columns= ["Date","Open","High","Low","Close","Volume"]
historical['Date'] = pd.to_datetime(historical['Date'], unit='s')
historical.set_index('Date', inplace=True)
historical.sort_values(by='Date', ascending=True, inplace=True)
historical
現(xiàn)在我們可以使用這些數(shù)據(jù)來創(chuàng)建一個簡單的指標并生成一個交互式燭臺圖。
Coinbase Pro API 不提供任何預(yù)設(shè)指標,但我們可以使用一些內(nèi)置的 pandas 功能來制作簡單指標,或者依靠 btalib 庫來制作更復(fù)雜的指標。
在本例中,我們將使用 pandas 創(chuàng)建一個簡單的 20 SMA 指標:
historical['20 SMA'] = historical.Close.rolling(20).mean()
historical.tail()
現(xiàn)在我們擁有使用 plotly 庫創(chuàng)建漂亮的交互式圖表所需的所有數(shù)據(jù):
import plotly.graph_objects as go
fig = go.Figure(data=[go.Candlestick(x = historical.index,
open = historical['Open'],
high = historical['High'],
low = historical['Low'],
close = historical['Close'],
),
go.Scatter(x=historical.index, y=historical['20 SMA'], line=dict(color='purple', width=1))])
fig.show()
可以使用get_product_order_book
Coinbase Pro API 端點獲取訂單簿數(shù)據(jù)。您需要指定要在其上設(shè)置訂單簿的資產(chǎn)。
讓我們獲取 BTC-USD 的訂單簿數(shù)據(jù),并將買入價和賣出價排列到單獨的 pandas 數(shù)據(jù)框中。之后,我將向您展示如何將兩者合并在一起。
order_book = c.get_product_order_book('BTC-USD')
order_book
現(xiàn)在我們創(chuàng)建兩個數(shù)據(jù)框:
bids = pd.DataFrame(order_book['bids'])
asks = pd.DataFrame(order_book['asks'])
bids.head()
現(xiàn)在我們將兩者合并,并將列重命名為信息豐富的名稱:
df = pd.merge(bids, asks, left_index=True, right_index=True)
df = df.rename({"0_x":"Bid Price","1_x":"Bid Size", "2_x":"Bid Amount",
"0_y":"Ask Price","1_y":"Ask Size", "2_y":"Ask Amount"}, axis='columns')
df.head()
可以使用端點通過 Coinbase Pro API 獲取交易數(shù)據(jù)get_product_trades
。必需參數(shù)是您要獲取數(shù)據(jù)的資產(chǎn)。
由于 Python 庫可能會因為進行幾個調(diào)用而卡住,因此我們將使用 REST API。
trades = pd.DataFrame(requests.get('https://api.pro.coinbase.com/products/ETH-USD/trades').json())
trades.tail()
Coinbase Pro WebSockets 可通過 WebscoketClient 端點訪問。借助此功能,您可以輕松流式傳輸并及時了解您感興趣的數(shù)據(jù)。
讓我們從一個獲取股票價格數(shù)據(jù)的基本 WebSocket 連接開始。
import cbpro
wsc = cbpro.WebsocketClient(url="wss://ws-feed.pro.coinbase.com",
products="ADA-USD",
channels=["ticker"])
要關(guān)閉 WebSocket,請編寫以下命令:
wsc.close()
現(xiàn)在,讓我們創(chuàng)建一個類,它將獲取一定數(shù)量的 WebSocket 消息的股票價格數(shù)據(jù)并將其打印出來:
import time, cbpro
class myWebsocketClient(cbpro.WebsocketClient):
def on_open(self):
self.url = "wss://ws-feed.pro.coinbase.com/"
self.products = ["ETH-USDT"]
self.channels=["ticker"]
self.message_count = 0
def on_message(self, msg):
self.message_count += 1
if 'price' in msg and 'type' in msg:
print ("Message type:", msg["type"],
"\t@ {:.3f}".format(float(msg["price"])))
def on_close(self):
print("Closing")
wsClient = myWebsocketClient()
wsClient.start()
print(wsClient.url, wsClient.products, wsClient.channels)
while (wsClient.message_count < 50):
print ("\nmessage_count =", "{} \n".format(wsClient.message_count))
time.sleep(1)
wsClient.close()
在這個第一個例子中,我將向您展示如何正確安全地啟動具有指定要求的訂單。我們想要做的是當(dāng) BTC 達到某個價格(例如 38500 美元)時啟動 ETH 交易。
為了實現(xiàn)這一點,我們需要設(shè)置訂單基礎(chǔ),然后創(chuàng)建一個循環(huán)來檢查價格水平是否被觸及。如果價格被觸及,我們將執(zhí)行市價訂單。否則,我們將繼續(xù)循環(huán)。
當(dāng)價格執(zhí)行后,我們會等待幾秒鐘并檢查訂單是否真的已完成。這一額外步驟對于添加到您的交易策略中非常重要,因為交易所服務(wù)器可能會遇到一些問題。
現(xiàn)在邏輯已經(jīng)設(shè)置好了,讓我們導(dǎo)入相關(guān)的庫并設(shè)置 API:
import cbpro
import base64
import json
from time import sleep
key = ''
secret = ''
passphrase = ''
encoded = json.dumps(secret).encode()
b64secret = base64.b64encode(encoded)
auth_client = cbpro.AuthenticatedClient(key=key, b64secret=secret, passphrase=passphrase)
c = cbpro.PublicClient()
現(xiàn)在來看看主要的交易邏輯。請注意我們?nèi)绾瓮ㄟ^采用當(dāng)前的 ETH-USD 價格并在其上方加幾美元來下限價訂單。這樣做是為了讓訂單更安全。
while True:
try:
ticker = c.get_product_ticker(product_id='BTC-USD')
except Exception as e:
print(f'Error obtaining ticker data: {e}')
if float(ticker['price']) >= 38500.00:
try:
limit = c.get_product_ticker(product_id='ETH-USD')
except Exception as e:
print(f'Error obtaining ticker data: {e}')
try:
order=auth_client.place_limit_order(product_id='ETH-USDT',
side='buy',
price=float(limit['price'])+2,
size='0.007')
except Exception as e:
print(f'Error placing order: {e}')
sleep(2)
try:
check = order['id']
check_order = auth_client.get_order(order_id=check)
except Exception as e:
print(f'Unable to check order. It might be rejected. {e}')
if check_order['status'] == 'done':
print('Order placed successfully')
print(check_order)
break
else:
print('Order was not matched')
break
else:
print(f'The requirement is not reached. The ticker price is at {ticker["price"]}')
sleep(10)
主要任務(wù)是當(dāng) BTC 在過去 5 分鐘內(nèi)波動 5% 時執(zhí)行 ETH 交易。這意味著我們需要創(chuàng)建一個循環(huán)來獲取兩種加密貨幣的價格并計算兩者之間的百分比變化。
如果百分比變化小于 5%,程序?qū)⑿菝?5 分鐘并再次計算百分比變化。如果百分比變化等于或大于 5%,則交易將執(zhí)行。
交易執(zhí)行后,我們將休眠幾秒鐘,然后檢查交易是否已完成。請記住,庫和 API 設(shè)置與上一個示例相同。
現(xiàn)在已經(jīng)設(shè)置了邏輯,是時候編寫代碼了:
while True:
try:
ticker_old = c.get_product_ticker(product_id='BTC-USD')
except Exception as e:
print(f'Error obtaining ticker data: {e}')
sleep(300)
try:
ticker_new = c.get_product_ticker(product_id='BTC-USD')
except Exception as e:
print(f'Error obtaining ticker data: {e}')
percent = ((float(ticker_new['price']) - float(ticker_old['price']))*100)/float(ticker_old['price'])
if percent >= 5:
try:
limit = c.get_product_ticker(product_id='ETH-USDT')
except Exception as e:
print(f'Error obtaining ticker data: {e}')
try:
order=auth_client.place_limit_order(product_id='ETH-USDT',
side='buy',
price=float(limit['price'])+2,
size='0.007')
except Exception as e:
print(f'Error placing order: {e}')
sleep(2)
try:
check = order['id']
check_order = auth_client.get_order(order_id=check)
except Exception as e:
print(f'Unable to check order. It might be rejected. {e}')
if check_order['status'] == 'done':
print('Order placed successfully')
print(check_order)
break
else:
print('Order was not matched')
break
else:
print(f'The requirement is not reached. The percent change is at {percent}')
要使用 Coinbase Pro API 取消訂單,您需要做的就是訪問cancel_order
API 端點并將訂單 ID 作為參數(shù)傳遞。
client.cancel_order(order_id = "ORDER-ID-HERE")