All
篩選條件:
我該如何將現金存入我的帳戶當中?
我需要帳戶驗證方面的幫助
為甚麼我無法訪問我的帳戶?
提取加密貨幣會產生任何費用嗎?
我需要協助登錄我的帳戶
檢索市場數據(例如:股票代號、訂單簿等)
做出交易決策(基於市場數據,或從市場數據衍生的指標)
下單/取消訂單
我們的 REST API 提供了實施功能齊全的交易機器人所需的所有功能,但了解如何結合我們 API 的不同方面可能很困難,因此提供以下交易機器人代碼作為範例。
範例代碼實施了一個基於指標的交易機器人(特別是 20 SMA,交易決策基於 1 minute 斜率變化),並展示了如何成功整合交易機器人的市場數據、決策制定和交易方面。
交易機器人代碼是一個單一的 Python 檔案,並直接與我們的 API 整合(沒有第三方 API 庫)。所有配置(API key、貨幣對、指標、訂單類型、槓桿等)都包含在代碼中,以便於參考。
範例代碼可在下方查看,也可以下載為 .py 檔案(REST_Indicator_Bot_Example.py)。
Python
#!/usr/bin/env python3
# Import required libraries (Python not API)
import time
import sys
import json
import base64
import hashlib
import hmac
import urllib.request
# Configure API key (copy/paste from account management)
api_key_public = 'COPY/PASTE API PUBLIC KEY HERE'
api_key_private = 'COPY/PASTE API PRIVATE KEY HERE'
# Configure market/orders/trades
trade_symbol = 'XXBTZUSD'
trade_interval = 1 # OHLC interval in minutes
trade_size = 0.0001 # Trade volume in base currency
trade_leverage = 2
# Initial indicator/trade variables
trade_direction = 0
sma_values = [0.0, 0.0, 0.0]
# Infinite loop (can be exited via keyboard interrupt)
try:
while True:
# Retrieve OHLC data at specified interval
print('Retrieving OHLC data ... ', end='')
try:
api_request = urllib.request.Request(
'https://api.kraken.com/0/public/OHLC?pair=%(symbol)s&interval=%(interval)d' % {
'symbol': trade_symbol, 'interval': trade_interval}
)
api_request.add_header('User-Agent', 'Kraken trading bot example')
api_response = urllib.request.urlopen(api_request).read().decode()
api_data = json.loads(api_response)
except Exception as error:
print('Failed (%s)' % error)
else:
print('Done' if len(api_data['error']) == 0 else 'Error (%s)' % api_data['error'])
# Calculate SMA (20 candles / closing price)
print('Calculating SMA 20 ... ', end='')
api_ohlc = api_data['result'][trade_symbol]
api_ohlc_length = len(api_ohlc) - 1
sma_temp = 0.0
for count in range(1, 21):
sma_temp += float(api_ohlc[api_ohlc_length - count][4])
sma_temp = sma_temp / 20
print('Done')
# Update SMA values
sma_values[2] = sma_values[1]
sma_values[1] = sma_values[0]
sma_values[0] = sma_temp
if sma_values[2] == 0.0:
print('Waiting %d seconds ... ' % (trade_interval * 60))
time.sleep(trade_interval * 60)
continue
else:
print('SMA 20 values ... %(sma2)f / %(sma1)f / %(sma0)f' % {
'sma2': sma_values[2], 'sma1': sma_values[1], 'sma0': sma_values[0]})
# Trading decision (change in slope of SMA)
print('Trading decision ... ', end='')
if (sma_values[0] > sma_values[1]) and (sma_values[1] < sma_values[2]):
make_trade = 1
print('Long')
elif (sma_values[0] < sma_values[1]) and (sma_values[1] > sma_values[2]):
make_trade = -1
print('Short')
else:
make_trade = 0
print('No trade')
# Place order/trade (if applicable)
if make_trade != 0:
print('Placing order/trade ... ', end='')
try:
api_path = '/0/private/AddOrder'
api_nonce = str(int(time.time() * 1000))
api_post = 'nonce=%(api_nonce)s&pair=%(symbol)s&type=%(direction)s&ordertype=market&volume=%(volume)f&leverage=%(leverage)s' % {
'api_nonce': api_nonce,
'symbol': trade_symbol,
'direction': 'buy' if make_trade == 1 else 'sell',
'volume': trade_size if trade_direction == 0 else trade_size * 2,
'leverage': str(trade_leverage) if trade_leverage > 0 else 'none'
}
api_sha256 = hashlib.sha256(api_nonce.encode('utf8') + api_post.encode('utf8'))
api_hmac = hmac.new(
base64.b64decode(api_key_private),
api_path.encode('utf8') + api_sha256.digest(),
hashlib.sha512
)
api_signature = base64.b64encode(api_hmac.digest())
api_request = urllib.request.Request(
'https://api.kraken.com/0/private/AddOrder', api_post.encode('utf8')
)
api_request.add_header('API-Key', api_key_public)
api_request.add_header('API-Sign', api_signature)
api_request.add_header('User-Agent', 'Kraken trading bot example')
api_response = urllib.request.urlopen(api_request).read().decode()
api_data = json.loads(api_response)
except Exception as error:
print('Failed (%s)' % error)
else:
trade_direction = make_trade
print('Done (%s)' % api_response if len(api_data['error']) == 0 else 'Error (%s)' % api_data['error'])
# Wait until next OHLC interval
print('Waiting %d seconds ... ' % (trade_interval * 60))
time.sleep(trade_interval * 60)
except KeyboardInterrupt:
sys.exit(0)
except Exception as error:
print('Error (%s)' % error)
sys.exit(1)請注意,此交易機器人僅作為範例,因此缺少一些理想的功能和必要的錯誤檢查,故不應用於生產交易(無法保證機器人會獲利)。