所有文章 > 学习各类API > Bittrex API – 入门指南
Bittrex API – 入门指南

Bittrex API – 入门指南

什么是 Bittrex API?

Bittrex API 是一种允许我们通过代码在 Bittrex 上自动交易加密货币的方法。

链接:https://bittrex.com

什么是Bittrex?

Bittrex 是一个在线加密货币交易平台,允许用户交易超过 700 个交易对。作为美国最古老的交易所之一,Bittrex 以其出色的安全实践和交易速度而闻名。

Bittrex API 免费吗?

创建 Bittrex 账户和使用 Bittrex API 完全免费,但交易时需要付费。费用取决于您交易的货币对和您的每月交易量。

每月交易量费用遵循做市商收费模式。这基本上意味着交易越多,费用越低。下图说明了收费方法。

挂单是指在进入订单簿后在市场上创造流动性的订单。这意味着挂单不会在下单时成交,而是等待未来与之匹配的订单。

另一方面,接受订单会从市场中获取流动性。它们通过与订单簿中已下达的另一个订单(即我们的订单制作者)进行匹配来立即执行。

说到交易费用,当用户将区块链上的代币转移到 Bittrex 或从 Bittrex 转移时,可能会产生一些特定的区块链网络费用。

Bittrex 不收取存款费,但收取取款费。

为什么我应该使用 Bittrex API?

  • Bittrex 免费使用
  • 拥有丰富的资产可供交易
  • 与其他交易所相比具有竞争力的费用
  • 拥有良好的 API
  • 拥有良好的业绩记录

为什么我不应该使用 Bittrex API?

  • Bittrex 需要更多功能,例如保证金交易
  • 糟糕的客户支持(用户可能要等待 3 个月以上才能收到回复)
  • 提款费用较高
  • 监管状态存在问题

Bittrex API 在我的国家/地区可用吗?

由于监管要求,居住在某些国家/地区的客户(见下图)将无法再使用 Bittrex 平台。此列表最后更新于 2021 年 3 月 23 日。

使用 Bittrex API 有哪些替代方案?

Bittrex 可以被其他更适合您需求的网站取代。以下是其中一些:

  • Coinbase
  • Binance
  • BitMex
  • Kraken
  • Gemini
  • FTX
  • KuCoin
  • Deribit
  • ByBit
  • Phemex
  • Bitfinex

如何开始使用 Bittrex API?

为了开始使用 Bittrex API,您首先需要访问其网站,网址为:

https://global.bittrex.com/

在右上角,你会看到“注册”按钮,请务必点击它并选择你的账户类型,填写你的电子邮件和密码。完成后,点击蓝色的“创建账户”按钮。

接下来是检查您的电子邮件中的验证链接,之后您将进入 ToS(服务条款)页面。

下一步是输入您的基本帐户信息,例如居住国家和出生详细信息。之后,您需要验证您的身份并提供一些其他信息。然后您需要等待几天才能通过 Bittrex 进行全面验证。

如何使用 Bittrex API 获取货币数据?

可以通过访问 Bittrex 货币端点,使用 Bittrex API 获取 Bittrex 上的货币数据。为此,我们将使用 REST API。

response = pd.DataFrame(requests.get('https://api.bittrex.com/v3/currencies').json())
response.tail()

如您所见,Bittrex 上有 444 种可用货币,它们通常附带“通知”消息,提供有关该货币的有用信息。

为了获取有关特定货币的信息,您可以调用以下端点并在末尾说明您的货币名称,如下所示:

btc = requests.get('https://api.bittrex.com/v3/currencies/BTC').json()
btc
{'symbol': 'BTC',
'name': 'Bitcoin',
'coinType': 'BITCOIN',
'status': 'ONLINE',
'minConfirmations': 2,
'notice': '',
'txFee': '0.00030000',
'IogoUrl': 'https://bittresblobstorage.blob.core.windows bef9.png',
'prohibitedIn': [],
'baseAddress': '1N52wHoVR79PMDishab2XmRHsbekCdGquK',
'associatedTermsOfServicel: [],
'tags': []}

如何在 Bittrex API 上获取价格数据?

可以通过调用指定货币和/或该货币的市场行情端点来获取 Bittrex API 的价格数据。

在我们访问某个股票代码之前,让我们先看看 Bittrex 交易所上所有可用的市场(又称交易对)是什么:

markets = pd.DataFrame(requests.get('https://api.bittrex.com/v3/markets').json())
markets.tail()

如您所见,Bittrex 上有超过 750 个可用的交易对。现在,让我们获取特定股票的价格数据。

ticker = requests.get('https://api.bittrex.com/v3/markets/BTC-USD/ticker').json()
ticker
{'symbol': 'BTCC-USD',
'last-TradeRate': '63552.35400000',
'bidRate': '63540.27100000',
'askRate': '63555.76000080'}

如果您想要所有可用交易对的价格数据,您可以编写以下内容:

tickers = pd.DataFrame(requests.get('https://api.bittrex.com/v3/markets/tickers').json())
tickers.tail()

如何使用 Bittrex API 获取历史数据?

Bittrex API 可以通过访问市场历史端点来获取历史价格数据,用户可以设置要获取的起始日期、股票代码和蜡烛间隔。

historical = pd.DataFrame(requests.get('https://api.bittrex.com/v3//markets/BTC-USD/candles/DAY_1/historical/2019').json())
historical.tail()

但是如果我们想用这些数据创建一些自定义指标和一个漂亮的交互式图表该怎么办呢?

如何使用 Bittrex API 访问 20 SMA 等技术指标?

Bittrex API 没有内置技术指标,但可以利用各种库创建自定义指标。例如,我们可以使用 pandas 滚动窗口创建 20 天简单移动平均线 (20 SMA)。

historical['20 SMA'] = historical.close.rolling(20).mean()
historical.tail()

对于更复杂的指标,您可以查看一个名为 btalib 的库。现在,让我们创建一个漂亮的交互式数据图表。

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()

如何使用 Bittrex API 获取订单簿数据?

可以使用 Bittrex REST API 市场订单簿端点获取订单簿数据。我还将向您展示如何为买入价和卖出价创建单独的数据框或合并的数据框。

orderbook = requests.get('https://api.bittrex.com/v3/markets/BTC-USD/orderbook').json()

# If you want separate data frames
bids = pd.DataFrame(orderbook['bid'])
asks = pd.DataFrame(orderbook['ask'])

# You can also merge the two into one
df = pd.merge(bids, asks, left_index=True, right_index=True)
df = df.rename({"rate_x":"Bid Price","quantity_x":"Bid Amount",
"rate_y":"Ask Price","quantity_y":"Ask Amount"}, axis='columns')
df.head()

当 BTC 达到某个价格时,如何使用 Bittrex API 对 ETH 执行交易?

在第一个示例中,我将向您展示如何正确安全地启动具有指定要求的订单。我们想要做的是当 BTC 达到特定价格(例如 50,000 美元)时启动 ETH 交易。

为了实现这一点,我们需要设置订单基础,然后创建一个循环来检查价格水平是否被触及。如果价格被触及,我们将执行市价订单。相反,我们将继续循环。

当价格执行后,我们会等待几秒钟并检查订单是否真的已完成。这一额外步骤对于添加到您的交易策略中非常重要,因为交易所服务器可能会遇到一些问题。

我们还将创建一个自定义函数,使我们更容易处理需要身份验证的 Bittrex 私有端点。

现在逻辑已经设置好了,让我们导入相关的库并设置交易:

import hmac
import time
import hashlib
import requests
import json
import pandas as pd

apiKey = ""
apiSecret = ""

def auth(uri, method, payload, apiKey, apiSecret):
timestamp = str(round(time.time()*1000))
contentHash = hashlib.sha512(payload).hexdigest()

array = [timestamp, uri, method, contentHash]
s= ''
preSign = s.join(str(v) for v in array)
signature = hmac.new(apiSecret.encode() ,preSign.encode(), hashlib.sha512).hexdigest()

headers = {
'Accept':'application/json',
'Api-Key':apiKey,
'Api-Timestamp':timestamp,
'Api-Content-Hash':contentHash,
'Api-Signature':signature,
'Content-Type':'application/json'
}

return headers

while True:
try:
ticker = requests.get('https://api.bittrex.com/v3/markets/BTC-USD/ticker').json()
except Exception as e:
print(f'Unable to obtain ticker data: {e}')

if float(ticker['bidRate']) >= 50000:

uri = 'https://api.bittrex.com/v3/orders'

content = { "marketSymbol":"USDC-ETH",
"direction":"SELL",
"type":"LIMIT",
"limit":"0.0005",
"quantity":"20",
"timeInForce":"GOOD_TIL_CANCELLED"
}

payload = bytes(json.dumps(content),'utf-8')

try:
data = requests.post(uri,
data=payload,
headers = auth(uri, 'POST', payload, apiKey, apiSecret),
timeout=10
).json()
print(data)
except Exception as e:
print(f'Unable to place order: {e}')

sleep(2)

try:
payload = ""
uri = f'https://api.bittrex.com/v3/orders/{data["id"]}'

check = requests.get(uri,
data=payload,
headers=auth(uri, 'GET', payload.encode(), apiKey, apiSecret),
timeout=10
).json()
print(check)
except Exception as e:
print(f'Unable to check order: {e}')

if check_order == 'OPEN':
print ('Order placed at {}'.format(pd.Timestamp.now()))
break
else:
print ('Order closed at {}'.format(pd.Timestamp.now()))
break
else:
sleep(60)
continue

请注意:如果您想交易其他美元对,符号通常会按相反的顺序排列,例如“ETH-USDT”。

当 BTC 在过去 5 分钟内波动 5% 时,如何使用 Bittrex API 执行 ETH 交易?

主要任务是当 BTC 在过去 5 分钟内波动 5% 时执行 ETH 交易。这意味着我们需要创建一个循环,以在特定间隔内获取 BTC 价格并计算它们之间的百分比变化。

如果百分比变化小于 5%,脚本将休眠 5 分钟并再次计算百分比变化。如果百分比变化等于或大于 5%,则交易将执行。

交易执行后,我们将休眠几秒钟,然后检查交易是否已完成。请记住,循环部分的代码与上一个示例相同。

现在已经设置了逻辑,是时候编写代码了:

while True:
try:
btc_old = requests.get('https://api.bittrex.com/v3/markets/BTC-USD/ticker').json()
except Exception as e:
print(f'Unable to obtain ticker data: {e}')

sleep(300)

try:
btc_new = requests.get('https://api.bittrex.com/v3/markets/BTC-USD/ticker').json()
except Exception as e:
print(f'Unable to obtain ticker data: {e}')

percent = (((float(btc_new['bidRate']) - float(btc_old['bidRate'])) * 100) / float(btc_old['bidRate']))

if percent >= 5:

uri = 'https://api.bittrex.com/v3/orders'

content = { "marketSymbol":"USDC-ETH",
"direction":"SELL",
"type":"LIMIT",
"limit":"0.0005",
"quantity":"20",
"timeInForce":"GOOD_TIL_CANCELLED"
}

payload = bytes(json.dumps(content),'utf-8')

try:
data = requests.post(uri,
data=payload,
headers = auth(uri, 'POST', payload, apiKey, apiSecret),
timeout=10
).json()
print(data)
except Exception as e:
print(f'Unable to place order: {e}')

sleep(2)

try:
payload = ""
uri = f'https://api.bittrex.com/v3/orders/{data["id"]}'

check = requests.get(uri,
data=payload,
headers=auth(uri, 'GET', payload.encode(), apiKey, apiSecret),
timeout=10
).json()
print(check)
except Exception as e:
print(f'Unable to check order: {e}')

if check_order == 'OPEN':
print ('Order placed at {}'.format(pd.Timestamp.now()))
break
else:
print ('Order closed at {}'.format(pd.Timestamp.now()))
break
else:
print(f'Requirment not reached. Percentage move at {percent}')
continue

如何使用 Bittrex API 取消订单?

要取消 Bittrex 的订单,您需要使用 DELETE 订单端点并传递要取消的订单的订单 ID。为此,您可以参考我们之前的示例:

uri = "https://api.bittrex.com/v3/orders/{orderId}"
payload = ""
data = requests.delete(uri,
data=payload,
headers = auth(uri, 'DELETE', payload.encode(), apiKey, apiSecret),
timeout=10
).json()

Bittrex API 可以在 Google Sheets 中使用吗?

是的,您可以通过编写一个简单的 JS 脚本在 Google Sheets 中使用 Bittrex API,该脚本对响应执行与我们的 Python 代码相同的操作。我将向您展示一个示例脚本,该脚本提取我们资产的最新股票价格。

我们需要做的第一件事是打开一个空白的 Google Sheets 表,然后转到工具并选择下拉菜单中出现的脚本编辑器。

到达那里后,您将复制以下代码并单击保存图标:

function Ticker_Last(symbol)
{
var url = "https://api.bittrex.com/v3/markets/" + symbol + "/ticker";
var response = UrlFetchApp.fetch(url);
var myjson = JSON.parse(response.getContentText());
var lastprice = myjson.lastTradeRate;
return lastprice;
}

现在您可以返回工作表并将您感兴趣的加密货币添加到单元格中。完成后,您可以使用以下函数提取最新价格数据:

=Ticker_Last(<cell>)
#你可能也喜欢这些API文章!