
Python調用Google Bard API 完整指南
請記住,期權費用不能超過期權價格的 12.5%。此外,期貨和期權合約有交割費,如下圖所示:
至于清算費用,則如下:
Deribit 不收取任何存款費用,而 BTC 的提款費用可能取決于比特幣網絡的當前狀態。
在為您的賬戶注資時,您只有一個選擇,那就是比特幣。這意味著 Deribit 不支持任何法定貨幣存款方式。
自2020年11月9日起,Deribit 要求所有新客戶獲得驗證身份才能進行交易。這意味著需要提供居住證明和身份證件。
自 2021 年起,Deribit 已無法訪問
如果您位于、注冊或以其他方式設立于下列國家/地區,或者是下列國家/地區的公民或居民:
Deribit 可以用其他更適合您需求的應用程序替代。以下是列表:
Deribit 擁有以下客戶:
請務必訪問以下 GitHub 來訪問這些客戶端:
https://github.com/deribit/deribit-api-clients
為了充分了解 Deribit API 的功能,我們首先需要開設一個帳戶以獲取 API 密鑰。我將向您展示幾個交易場景,我們需要的帳戶是此鏈接上的測試帳戶:
測試版和正式版 Deribit 賬戶的注冊流程基本相同。以下是正式版網站的鏈接:
到達那里后,你會看到一個帳戶創建框。請務必點擊綠色的“創建帳戶”按鈕,然后填寫你的電子郵件地址、昵稱、創建密碼并選擇你的國家/地區。
之后,您將收到來自 Deribit 的驗證電子郵件。請務必仔細檢查并確認。完成后,您將進入以下屏幕:
現在,我們需要的是 API 密鑰。為此,請轉到右上角的個人資料圖標,然后單擊“設置”。之后,導航到 API 部分并單擊“添加新密鑰”按鈕。
會出現一個彈出屏幕,提示您分配新 API 密鑰的主要功能。選項范圍從帳戶到托管權限。在本文中,我將為它們全部賦予讀取 + 寫入權限。
批準后,將創建 API 密鑰,您將清楚地看到您的客戶端 ID 和客戶端密鑰。您還可以執行多種操作,例如二維碼、重置密鑰、刪除密鑰等。
由于我們需要的一切都已設置好,以下標題將從主要公共端點開始探索 API,并以兩個交易場景中的私有 API 順序結束。
為了獲取 Deribit 提供的所有貨幣,您可以使用 get_currencies 端點。我們將導入所需的庫并以以下方式調用其 API:
import asyncio
import websockets
import json
import pandas as pd
import pprint
import nest_asyncio
nest_asyncio.apply()
msg = \
{
"jsonrpc" : "2.0",
"id" : 7538,
"method" : "public/get_currencies",
"params" : {
}
}
async def call_api(msg):
async with websockets.connect('wss://test.deribit.com/ws/api/v2') as websocket:
await websocket.send(msg)
while websocket.open:
response = await websocket.recv()
json_par = json.loads(response)
print(json_par)
return(json_par)
response = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))
由于響應看起來不太好,我們將使用 pprint 庫來漂亮地打印它。
pprint.pprint(response)
更好的是,讓我們在函數中添加 pprint 作為我們的主要打印方式,并調用下一個將獲取價格數據的端點。
有多個 Deribit 端點包含價格數據,但最“精確”的是公共行情端點。讓我們更新該函數以獲得更漂亮的打印效果。
msg = {
"jsonrpc" : "2.0",
"id" : 8106,
"method" : "public/ticker",
"params" : {
"instrument_name" : "BTC-PERPETUAL"
}
}
async def call_api(msg):
async with websockets.connect('wss://test.deribit.com/ws/api/v2') as websocket:
await websocket.send(msg)
while websocket.open:
response = await websocket.recv()
json_par = json.loads(response)
pprint.pprint(json_par)
return(json_par)
response = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))
如果您想獲取指數價格,您可以使用“get_index_price”端點。
msg = {"jsonrpc": "2.0",
"method": "public/get_index_price",
"id": 42,
"params": {
"index_name": "btc_usd"}
}
response = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))
{'id': 42,
'jsonrpc': '2.0',
'result': {'estimated_delivery_price': 57848.15, 'index price': 57848.15},
'testnet': True,
'usDiff': 177,
'usIn': 1616071078267979,
'usOut': 16160710782681561}
Deribit 提供了一些歷史數據端點,例如資金利率歷史和歷史波動率。讓我們從后者開始,獲取這兩個數據:
msg = {
"jsonrpc" : "2.0",
"id" : 8387,
"method" : "public/get_historical_volatility",
"params" : {
"currency" : "BTC"
}
}
response = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))
我們要做的下一步是將響應放入 pandas 數據框中,以便以后使用。
volatility = pd.DataFrame(response['result'])
volatility.head()
為了獲取有關數據框的一些基本統計數據,您可以使用 pd.describe 函數:
pd.set_option('precision', 3)
volatility.describe()
現在來看看融資利率的歷史:
msg = {
"jsonrpc" : "2.0",
"id" : 7617,
"method" : "public/get_funding_rate_history",
"params" : {
"instrument_name" : "BTC-PERPETUAL",
"start_timestamp" : 1569888000000,
"end_timestamp" : 1569902400000
}
}
response = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))
訂單簿數據可以通過使用公共 get_order_book 端點獲取。交易所未指定訂單簿的最大層級深度。我們將使用層級 25 作為請求:
msg = {
"jsonrpc" : "2.0",
"id" : 8772,
"method" : "public/get_order_book",
"params" : {
"instrument_name" : "BTC-PERPETUAL",
"depth" : 25
}
}
response = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))
我們現在應該通過提取其中的重要部分來清理響應。為此,我將為買入價和賣出價創建單獨的數據框,然后將兩者合并在一起。
bids = pd.DataFrame(response['result']['bids'])
asks = pd.DataFrame(response['result']['asks'])
book = pd.merge(bids, asks, left_index=True, right_index=True)
book.head()
如果您想重命名列,您可以傳遞以下命令:
book = df.rename({"0_x":"Bid Price","1_x":"Bid Amount",
"0_y":"Ask Price","1_y":"Ask Amount"}, axis='columns')
交易(又稱交易)可通過使用按貨幣或按工具獲取交易端點從 Deribit 獲取。對于結算,您只需在請求消息中將“交易”更改為“結算”。
讓我們從前者開始,按貨幣獲取交易和結算:
msg = {
"jsonrpc" : "2.0",
"id" : 9290,
"method" : "public/get_last_trades_by_currency",
"params" : {
"currency" : "BTC",
"count" : 2
}
}
response = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))
現在談談定居點:
msg = {
"jsonrpc" : "2.0",
"id" : 4497,
"method" : "public/get_last_settlements_by_currency",
"params" : {
"currency" : "BTC",
"type" : "delivery",
"count" : 2
}
}
response = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))
Deribit 提供多種可通過其端點啟動的訂單類型。但在我們逐一介紹每種訂單類型并編寫兩個交易方案之前,我們應該先了解一下訂單由哪些參數組成。
基本訂單參數如下:
instrument_name
– 您的資產名稱(必填)amount
– 要求的訂單大小(必填)type
– 默認為“limit”,但可以是stop_limit,market,stop_marketlabel
– 用戶定義的訂單標簽price
– 基礎貨幣的訂單價格僅適用于限價訂單和止損限價訂單。time_in_force
– 指定訂單持續多長時間。可以是“good_til_cancelled”、“fill_or_kill”、“immediate_or_cancel”。max_show
– 訂單中向其他客戶顯示的最大金額(例如,0 表示訂單不可見)post_only
– “如果為真,則訂單被視為僅后送訂單。如果新價格會導致訂單立即成交(作為接受者),則價格將更改為略低于價差。僅與 time_in_force = 結合使用才有效good_til_cancelled
”reject_post_only
– “如果訂單被視為僅發布訂單,并且此字段設置為 true,則訂單將不經修改地放入訂單簿,或者請求被拒絕并且訂單被取消。”reduce_only
– 如果為真,則降低當前位置stop_price
– 止損限價單的止損價trigger
– 它定義了 stop_limit 和 stop_market 訂單的觸發類型。advanced
– 高級期權訂單類型(僅適用于期權)mmp
– 訂購 MMP 標志現在我們已經了解了主要的訂單構建模塊,接下來讓我們探索一些特殊的訂單構建模塊以及如何啟動它們。
Deribit 中的所有訂單都具有類似的結構,如最后一個標題所示。這意味著,為了觸發永續合約的訂單,我們只需指定正確的工具名稱(例如 BTC-PERPETUAL)。
訂單信息的示例如下:
msg = {
"jsonrpc" : "2.0",
"id" : 4122,
"method" : "private/cancel_all_by_instrument",
"params" : {
"instrument_name" : "BTC-PERPETUAL",
"type" : "all"
}
}
如果您跳過此部分,這是我們用來發送請求的函數:
async def call_api(msg):
async with websockets.connect('wss://test.deribit.com/ws/api/v2') as websocket:
###############
# Before sending a message, make sure that your connection
# is authenticated (use public/auth call before)
###############
await websocket.send(msg)
while websocket.open:
response = await websocket.recv()
json_par = json.loads(response)
print(json_par)
return(json_par)
Deribit 永續合約的特點是持續測量合約標記價格與 Deribit BTC 指數之間的差額。
這兩個價格水平之間的百分比差異是適用于所有未平倉永續合約的 8 小時融資利率的基礎。有關更多信息,請訪問以下鏈接:
https://www.deribit.com/pages/docs/perpetual
Deribit 中的所有訂單都具有類似的結構。這意味著,為了觸發期貨合約的訂單,我們只需指定正確的工具名稱(例如 BTC-24SEP21)。
訂單信息的示例如下:
msg = {
"jsonrpc" : "2.0",
"id" : 4122,
"method" : "private/cancel_all_by_instrument",
"params" : {
"instrument_name" : "BTC-24SEP21",
"type" : "all"
}
}
Deribit 上的比特幣期貨以現金結算,而非通過“實物”交割 BTC 進行結算。這意味著在結算時,BTC 期貨的買家不會購買實際的 BTC,賣家也不會出售 BTC。
只有在合約結算時才會根據到期價格(以 BTC 價格指數的最近 30 分鐘平均值計算)轉移損失/收益。有關更多信息,請訪問以下鏈接:
https://www.deribit.com/pages/docs/futures
Deribit 中的所有訂單都具有類似的結構。這意味著,為了觸發期貨合約的訂單,我們只需指定正確的工具名稱(例如 ETH-19MAR21)。
訂單信息的示例如下:
msg = {
"jsonrpc" : "2.0",
"id" : 4122,
"method" : "private/cancel_all_by_instrument",
"params" : {
"instrument_name" : "ETH-19MAR21",
"type" : "all"
}
}
Deribit 遵循歐式現金結算期權,這意味著期權僅在到期時行使,不能提前行使。在 Deribit 上,這將自動發生。
更多信息請訪問以下鏈接:
https://www.deribit.com/pages/docs/options
在此示例中,我將向您展示如何正確安全地啟動具有指定要求的訂單。我們想要做的是當 BTC 達到特定價格時啟動 ETH 交易。
為了實現這一點,我們需要設置訂單基礎,然后創建一個循環來檢查價格水平是否被觸及。如果價格被觸及,我們將執行市價訂單。否則,我們將繼續循環。
當價格執行后,我們會等待幾秒鐘,然后檢查訂單是否已完成。這一額外步驟對于您的交易策略非常重要,因為交易所服務器可能會遇到一些問題。
讓我們繼續導入相關庫并設置主交易循環。
#Order Foundation
import asyncio
import websockets
import json
import pandas as pd
from time import sleep
import pprint
import hmac
import hashlib
from datetime import datetime
import nest_asyncio
nest_asyncio.apply()
async def call_api(msg):
async with websockets.connect('wss://test.deribit.com/ws/api/v2') as websocket:
await websocket.send(msg)
while websocket.open:
response = await websocket.recv()
json_par = json.loads(response)
#print(json_par)
return(json_par)
clientId = "TzxHdA_N"
clientSecret = "3LsbOcO7Fqzv_oT9-RDy1JwvYG7uR3NnF5HXDnvn6AA"
timestamp = round(datetime.now().timestamp() * 1000)
nonce = "123"
data = ""
signature = hmac.new(
bytes(clientSecret, "latin-1"),
msg=bytes('{}\n{}\n{}'.format(timestamp, nonce, data), "latin-1"),
digestmod=hashlib.sha256).hexdigest().lower()
auth_msg = {
"jsonrpc" : "2.0",
"id" : 42,
"method" : "public/auth",
"params" : {
"grant_type" : "client_signature",
"client_id" : clientId,
"timestamp" : timestamp,
"signature" : signature,
"nonce" : nonce,
"data" : data
}
}
price_msg = {
"jsonrpc" : "2.0",
"id" : 42,
"method" : "public/ticker",
"params" : {
"instrument_name" : "BTC-PERPETUAL"
}
}
order_msg = {
"jsonrpc" : "2.0",
"id" : 42,
"method" : "private/buy",
"params" : {
"instrument_name" : "ETH-PERPETUAL",
"amount" : 5,
"type" : "market",
"label" : "algoorder"
}
}
check_order = {
"jsonrpc" : "2.0",
"id" : 42,
"method" : "private/get_order_state",
"params" : {
"order_id" : "ETH-331562"
}
}
#Main order loop
while True:
try:
btc = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(price_msg)))
except exception as e:
print("Unable to obtain BTC price")
if btc['result']['best_ask_price'] < 58800.0:
print("The price mark was not reached.")
sleep(60)
continue
elif btc['result']['best_ask_price'] >= 58800.0:
try:
auth = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(auth_msg)))
pprint.pprint(auth)
except exception as e:
print('There was an authentication error')
try:
order = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(order_msg)))
#print(order)
except exception as e:
print("Error occurred while placing order")
sleep(2)
try:
order_check = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(check_order)))
pprint.pprint(order_check)
except excpetion as e:
print("Error checking order")
if order_check['result']['order_state'] == 'filled' or order_check['result']['order_state'] == "open":
print ('Order placed at {}'.format(pd.Timestamp.now()))
break
else:
print('Order was canceled {}'.format(pd.Timestamp.now()))
break
如果我們想計算兩種貨幣之間的百分比變動,然后下訂單,該怎么辦?好吧,這個例子將解決這個問題!
主要任務是當 BTC 在過去 5 分鐘內波動 5% 時執行 ETH 交易。這意味著我們需要創建一個循環來獲取兩種加密貨幣的價格并計算兩者之間的百分比變化。
如果百分比變化小于 5%,算法將休眠 5 分鐘并再次計算百分比變化。如果百分比變化等于或大于 5%,則交易將執行。
交易執行后,我們將休眠幾秒鐘,然后檢查交易是否已完成。現在邏輯已經設置好,是時候編寫代碼了:
clientId = "ID_HERE"
clientSecret = "SECRET_HERE"
timestamp = round(datetime.now().timestamp() * 1000)
nonce = "123"
data = ""
signature = hmac.new(
bytes(clientSecret, "latin-1"),
msg=bytes('{}\n{}\n{}'.format(timestamp, nonce, data), "latin-1"),
digestmod=hashlib.sha256).hexdigest().lower()
auth_msg = {
"jsonrpc" : "2.0",
"id" : 42,
"method" : "public/auth",
"params" : {
"grant_type" : "client_signature",
"client_id" : clientId,
"timestamp" : timestamp,
"signature" : signature,
"nonce" : nonce,
"data" : data
}
}
btc_price_msg = {
"jsonrpc" : "2.0",
"id" : 42,
"method" : "public/ticker",
"params" : {
"instrument_name" : "BTC-PERPETUAL"
}
}
order_msg = {
"jsonrpc" : "2.0",
"id" : 42,
"method" : "private/buy",
"params" : {
"instrument_name" : "ETH-PERPETUAL",
"amount" : 5,
"type" : "market",
"label" : "algoorder"
}
}
check_order = {
"jsonrpc" : "2.0",
"id" : 42,
"method" : "private/get_order_state",
"params" : {
"order_id" : "ETH-331562"
}
}
while True:
try:
btc_old = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(btc_price_msg)))
except exception as e:
print("Unable to obtain BTC price")
sleep(300)
try:
btc_new = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(btc_price_msg)))
except exception as e:
print("Unable to obtain BTC price")
percent = (btc_new['result']['best_ask_price'] - btc_old['result']['best_ask_price'] * 100) / btc_old['result']['best_ask_price']
if percent < 5:
print("The requirement was not fulfilled.")
sleep(0.1)
continue
elif percent >= 5:
try:
auth = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(auth_msg)))
pprint.pprint(auth)
except exception as e:
print('There was an authentication error')
try:
order = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(order_msg)))
#print(order)
except exception as e:
print("Error occurred while placing order")
sleep(2)
try:
order_check = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(check_order)))
pprint.pprint(order_check)
except excpetion as e:
print("Error checking order")
if order_check['result']['order_state'] == 'filled' or order_check['result']['order_state'] == "open":
print ('Order placed at {}'.format(pd.Timestamp.now()))
break
else:
print('Order was canceled {}'.format(pd.Timestamp.now()))
break
如果您想取消并使用 Deribit 下訂單,您可以傳遞類似以下請求:
msg = \
{
"jsonrpc" : "2.0",
"id" : 4214,
"method" : "private/cancel",
"params" : {
"order_id" : "ETH-SLIS-12"
}
}
async def call_api(msg):
async with websockets.connect('wss://test.deribit.com/ws/api/v2') as websocket:
###############
# Before sending the message, make sure that your connection
# is authenticated (use public/auth call before)
###############
await websocket.send(msg)
while websocket.open:
response = await websocket.recv()
# do something with the response...
print(response)
asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))