LoginSignup
8
7

More than 3 years have passed since last update.

BitmexのAPIを触ってみました。

Last updated at Posted at 2019-07-15

bitmexのbot作成に必要なAPIを関数化してみました。
(とりあえず動かしてみたものなので、ログ出し関連は雑です。)

インジケータ作成器と合わせて使えばサクっと動かせそう。
https://qiita.com/redmeteor777/items/464e2a5ce29683a143b3

価格情報取得はbitmexからじゃなくCryptowatchを使う予定なのでここには未実装。

注文
create_order

未約定の注文があるかの確認(戻り値で注文IDを返す)
check_order

未約定の注文をキャンセル(注文IDが必要)
cancel_order(id)

口座残高の取得
get_collateral

ポジション情報の取得
get_position

[別ファイルにAPIキーを保存しておきます。]

const.py
# APIキーを設定
apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxx'

# APIシークレットを設定
secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

[APIをまとめたファイル]

bitmex_API.py


import ccxt
import numpy as np
from datetime import datetime
import time

# 定義ファイル
import const

# 売買注文を行う関数
def create_order(symbol, type, side, amount, price=None):

    """
    引数
    symbol(str) : 'BTC/USD'
    type(str) : 'Limit' -> 指値 / 'Market' -> 成行
    side(str) : 'Buy' -> 買い / 'Sell' -> 売り
    amount(float/int) -> 注文枚数
    price(float/int) -> 注文価格(成行の場合は省略可)
    """

    # ccxtの読み込み
    bitmex = ccxt.bitmex()
    bitmex.apiKey = const.apiKey # APIキーを設定
    bitmex.secret = const.secret # APIシークレットを設定

    while True:
        result = {}

        try:
            # 注文を実行

            create_order = bitmex.private_post_order({
                'symbol' : symbol,
                'type' : type,
                'side' : side,
                'orderQty' : amount,
                'price' : price
                })


            return create_order

        except ccxt.BaseError as e:
            print("Failed Post Order : " + str(e))
            time.sleep(20)

# 売買注文の約定確認を行う関数
def check_order():
    """
    引数 : なし
    戻り値 : 未約定の注文ID
    """
    while True:
        try:
            print("---------- Checking Order ----------")

            # ccxtの読み込み
            bitmex = ccxt.bitmex()
            bitmex.apiKey = const.apiKey # APIキーを設定
            bitmex.secret = const.secret # APIシークレットを設定

            orders = []
            order_id = []
            len_orders = 0
            orders = bitmex.fetch_open_orders()

            if len(orders) > 0:
                len_orders = len(orders)
                print("---------- {} Order Remaining ----------".format(len_orders))

                for i in orders:
                    order_id.append(i['info']['orderID'])

                print(order_id)

            elif orders == []:
                print("---------- Nothing Order ----------")
                order_id = 0

            return order_id

        except ccxt.BaseError as e:
            print("Failed Check Order : " + str(e))
            time.sleep(20)

# 売買注文のキャンセルを行う関数
def cancel_order(order_id):
    """
    引数 : なし
    戻り値 : キャンセルの結果(全部成功=1、それ以外=0)
    """
    while True:
        try:
            print("---------- Cancel Order ----------")

            # ccxtの読み込み
            bitmex = ccxt.bitmex()
            bitmex.apiKey = const.apiKey # APIキーを設定
            bitmex.secret = const.secret # APIシークレットを設定

            cancel_order = []

            if order_id != 0:
                for i in order_id:
                    cancel_result = bitmex.cancel_order(i)
                    cancel_order.append(cancel_result['info']['ordStatus'])


            return cancel_order

        except ccxt.BaseError as e:
            print("Failed Cancel Order : " + str(e))
            time.sleep(20)

# 口座残高を取得する関数
def get_collateral():
    """
    引数 : なし
    戻り値 
        result['total'] # 証拠金総額
        result['used'] # 拘束中証拠金
        result['free'] # 使用可能証拠金
    """

    # ccxtの読み込み
    bitmex = ccxt.bitmex()
    bitmex.apiKey = const.apiKey # APIキーを設定
    bitmex.secret = const.secret # APIシークレットを設定

    while True:
        result = {}
        try:
            # 口座残高を取得
            collateral = bitmex.fetch_balance()
            # 総額
            result['total'] = collateral['BTC']['total']
            # 拘束中
            result['used'] = collateral['BTC']['used']
            # 使用可能
            result['free'] = collateral['BTC']['free']

            return result

        except ccxt.BaseError as e:
            print_log("Failed Get Balance : " + str(e))
            time.sleep(20)

# ポジション情報を取得する関数
def get_position():
    """
    引数 : なし
    戻り値 
        result['side'] # None->ノーポジ、BUY->ロング、SELL->ショート
        result['used'] # 拘束中証拠金
        result['free'] # 使用可能証拠金
        result['lots'] # ロットサイズ
        result['averageprice'] # 全ロットの平均価格
    """

    # ccxtの読み込み
    bitmex = ccxt.bitmex()
    bitmex.apiKey = const.apiKey # APIキーを設定
    bitmex.secret = const.secret # APIシークレットを設定

    while True:
        result = {}
        try:

            position = bitmex.private_get_position()

            if position == []:
                result['side'] = 'NONE'
                result['lots'] = 0
            else:
                result['lots'] = abs(float(position[0]['currentQty']))
                result['averageprice'] = float(position[0]['avgEntryPrice'])

                if position[0]['currentQty'] < 0:
                    result['side'] = 'SELL'
                elif position[0]['currentQty'] > 0:
                    result['side'] = 'BUY'

            return result

        except ccxt.BaseError as e:
            print_log("Failed Get Positions : " + str(e))
            time.sleep(20)

            return result
8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7