Welcome to python-binance v0.6.2¶
これは Binance exchange REST API v1/3 の非公式のPythonラッパーです。使用に関しては、リスクを理解してご自身の責任においてご利用ください。
Binance で仮想通貨を通常の手続きで購入するには、 こちら からご利用ください。仮想通貨取引を自動化したい場合は、引き続きこのドキュメントをお読みください。
- Source code
- https://github.com/sammchardy/python-binance
- Documentation
- https://python-binance-jp.readthedocs.io/ja/latest/
- Binance API Telegram
- https://t.me/binance_api_english
- Blog with examples
- https://sammchardy.github.io
定期的に Changelog を確認し、新機能の追加やバグ修正がないかをチェックしてください。
主な機能¶
- 全ての通常機能、マーケットデータ、口座のエンドポイントの実装
- 使いやすい認証処理
- タイムスタンプを自分で生成する必要はありません。ラッパーが行います。
- レスポンスのエラーハンドリング
- 再接続機能付きのウェブソケットの接続処理と複数接続
- 通貨ペアのデプスキャッシュ
- Kline/ローソク足のヒストリカルデータ取得関数
- 出金機能
- デポジットアドレス
クイックスタート¶
API Keyの生成 と許可設定
pip install python-binance
from binance.client import Client
client = Client(api_key, api_secret)
# マーケットデプスの取得
depth = client.get_order_book(symbol='BNBBTC')
# テスト成行注文 実際の注文を送信するには、create_order関数を使用
order = client.create_test_order(
symbol='BNBBTC',
side=Client.SIDE_BUY,
type=Client.ORDER_TYPE_MARKET,
quantity=100)
# 全ての仮想通貨ペアの価格取得
prices = client.get_all_tickers()
# 100 ETH出金
# 出金に関しては、docs参照
from binance.exceptions import BinanceAPIException, BinanceWithdrawException
try:
result = client.withdraw(
asset='ETH',
address='<eth_address>',
amount=100)
except BinanceAPIException as e:
print(e)
except BinanceWithdrawException as e:
print(e)
else:
print("Success")
# 出金履歴リストの取得
withdraws = client.get_withdraw_history()
# ETH出金のリストを取得
eth_withdraws = client.get_withdraw_history(asset='ETH')
# BTCのデポジットアドレスを取得
address = client.get_deposit_address(asset='BTC')
# BNBBTC用のトレードウェブソケットの開始
def process_message(msg):
print("message type: {}".format(msg['e']))
print(msg)
# 処理を記述
from binance.websockets import BinanceSocketManager
bm = BinanceSocketManager(client)
bm.start_aggtrade_socket('BNBBTC', process_message)
bm.start()
# 任意の日付範囲のklineヒストリカルデータの取得
# 前日から今までの1 minute klinesを取得
klines = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC")
# 2017年12月の30 minute klinesを取得
klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1 Dec, 2017", "1 Jan, 2018")
# 上場からのweekly klinesを取得
klines = client.get_historical_klines("NEOBTC", KLINE_INTERVAL_1WEEK, "1 Jan, 2017")
詳細は、 ドキュメント をお読みください。
Contents¶
はじめに¶
インストール¶
python-binance
は pip
により PYPI からインストールできます。
pip install python-binance
Windows
ビルドエラーが発生する場合、Microsoft Visual C++が必要です。 Python Wiki on Widows Compilers を参照して、Visual C++ Build Toolsをインストールしてください。
Binanceでの登録¶
まず最初に、 Binanceで登録 してください。
API Keyの取得¶
登録した口座でプログラムを使用するには、 API Keyを作成 する必要があります。
クライアントの初期化¶
API KeyとSecretを設定します。
from binance.client import Client
client = Client(api_key, api_secret)
APIの呼び出し¶
Binance API documentation で設定されているキーワードと同じ単語を使用した各メソッドは、任意のパラメータを対応したエンドポイントに渡します。
Binance API documentation に記載されている通り、各メソッドは、JSONレスポンスのディクショナリーを返します。 各メソッドのコードのdocstringは、元となったエンドポイントの内容を参照しています。
Binance API documentationは、 timestamp パラメータを参照しますが、要求される場合は生成されます。
メソッドによっては recvWindow パラメータがあります。 タイミングセキュリティーのために使用されます。詳細はBinance documentationを参照してください。
APIエンドポイントのレートリミットは、Binanceにより秒間20リクエストに制限されています。制限を解除したい場合は、直接お問い合わせください。
APIレートリミット¶
get_exchange_info() を確認して、最新のレートリミットに関する情報を入手してください。
現時点でのBinanceのレートリミット:
- 1分間に1200リクエスト
- 1秒間に10の注文
- 24時間に100,000の注文
呼び出すメソッドによっては、全ての通貨ペアの情報を読み込む場合など、他のメソッドよりも負荷がかかる場合があります。 詳細は、 official Binance documentation をご確認ください。
Requestの設定¶
python-binance は、 requests ライブラリを使用します。
クライアントを作成後、全てのAPIコールに対し、カスタムリクエストパラメータを設定できます。
client = Client("api-key", "api-secret", {"verify": False, "timeout": 20})
どのAPIコールでも、デフォルト設定をオーバーライドまたは再設定することにより、カスタムリクエストパラメータを送信することができます。
# get_all_ordersのコールはverify: False and timeout: 5 の結果になることがあります。
client = Client("api-key", "api-secret", {"verify": False, "timeout": 20})
client.get_all_orders(symbol='BNBBTC', requests_params={'timeout': 5})
全てのオプションについては、 requests documentation を参照してください。
プロキシ設定
上記のリクエスト設定を使用することができます。
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080'
}
# クライアント初期化
client = Client("api-key", "api-secret", {'proxies': proxies})
# または、個別のコール
client.get_all_orders(symbol='BNBBTC', requests_params={'proxies': proxies})
または、リクエスト処理に必要な場合は、プロキシ環境変数を設定することもできます。
Linux 環境変数の設定例(参照: requests Proxies documentation )は下記の通りです。
$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="http://10.10.1.10:1080"
Windows環境の場合
C:\>set HTTP_PROXY=http://10.10.1.10:3128
C:\>set HTTPS_PROXY=http://10.10.1.10:1080
列挙型¶
Binanceは、Order Types, Order Side, Time in Force, Order response, Kline intervalsに対して列挙型を提供しています。 binance.client.Client で確認することができます。
SYMBOL_TYPE_SPOT = 'SPOT'
ORDER_STATUS_NEW = 'NEW'
ORDER_STATUS_PARTIALLY_FILLED = 'PARTIALLY_FILLED'
ORDER_STATUS_FILLED = 'FILLED'
ORDER_STATUS_CANCELED = 'CANCELED'
ORDER_STATUS_PENDING_CANCEL = 'PENDING_CANCEL'
ORDER_STATUS_REJECTED = 'REJECTED'
ORDER_STATUS_EXPIRED = 'EXPIRED'
KLINE_INTERVAL_1MINUTE = '1m'
KLINE_INTERVAL_2MINUTE = '3m'
KLINE_INTERVAL_5MINUTE = '5m'
KLINE_INTERVAL_15MINUTE = '15m'
KLINE_INTERVAL_30MINUTE = '30m'
KLINE_INTERVAL_1HOUR = '1h'
KLINE_INTERVAL_2HOUR = '2h'
KLINE_INTERVAL_4HOUR = '4h'
KLINE_INTERVAL_6HOUR = '6h'
KLINE_INTERVAL_8HOUR = '8h'
KLINE_INTERVAL_12HOUR = '12h'
KLINE_INTERVAL_1DAY = '1d'
KLINE_INTERVAL_3DAY = '3d'
KLINE_INTERVAL_1WEEK = '1w'
KLINE_INTERVAL_1MONTH = '1M'
SIDE_BUY = 'BUY'
SIDE_SELL = 'SELL'
ORDER_TYPE_LIMIT = 'LIMIT'
ORDER_TYPE_MARKET = 'MARKET'
ORDER_TYPE_STOP_LOSS = 'STOP_LOSS'
ORDER_TYPE_STOP_LOSS_LIMIT = 'STOP_LOSS_LIMIT'
ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT'
ORDER_TYPE_TAKE_PROFIT_LIMIT = 'TAKE_PROFIT_LIMIT'
ORDER_TYPE_LIMIT_MAKER = 'LIMIT_MAKER'
TIME_IN_FORCE_GTC = 'GTC'
TIME_IN_FORCE_IOC = 'IOC'
TIME_IN_FORCE_FOK = 'FOK'
ORDER_RESP_TYPE_ACK = 'ACK'
ORDER_RESP_TYPE_RESULT = 'RESULT'
ORDER_RESP_TYPE_FULL = 'FULL'
Websocket Depth に関しては、 binance.websockets.BinanceSocketManager で確認することができます。
WEBSOCKET_DEPTH_5 = '5'
WEBSOCKET_DEPTH_10 = '10'
WEBSOCKET_DEPTH_20 = '20'
コード内で使用するには、binance.client.Client または binance.websockets.BinanceSocketManagerを参照してください。
from binance.client import Client
from binance.websockets import BinanceSocketManager
side = Client.SIDE_BUY
一般的なエンドポイント¶
サーバーへPing送信¶
client.ping()
マーケットデータエンドポイント¶
マーケットデプスの取得¶
depth = client.get_order_book(symbol='BNBBTC')
最近のトレードを取得¶
trades = client.get_recent_trades(symbol='BNBBTC')
トレードのヒストリカルデータを取得¶
trades = client.get_historical_trades(symbol='BNBBTC')
Kline/ローソク足を取得¶
candles = client.get_klines(symbol='BNBBTC', interval=Client.KLINE_INTERVAL_30MINUTE)
Kline/ローソク足のヒストリカルデータを取得¶
klineの日付範囲指定・インターバル指定のデータを取得する。
# 前日から現在までの1 minute klinesを取得
klines = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC")
# klineの2017年12月のデータを取得
klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1 Dec, 2017", "1 Jan, 2018")
# 上場以来のweekly klinesを取得
klines = client.get_historical_klines("NEOBTC", KLINE_INTERVAL_1WEEK, "1 Jan, 2017")
24hr Tickerを取得¶
tickers = client.get_ticker()
Orderbook Tickersを取得¶
全てのマーケットのオーダーブックの、最初のbidとaskのエントリーを取得
tickers = client.get_orderbook_tickers()
アカウントエンドポイント¶
注文¶
注文バリデーション¶
Binanceには、通貨ペアの注文に対して、最低価格、数、総注文価格についてのルールがあります。
詳細は、 Filters のオフィシャルAPIのセクションを参照してください。
下記のスニペットを参考に、出力の整形をしてください。
amount = 0.000234234
precision = 5
amt_str = "{:0.0{}f}".format(amount, precision)
注文送信¶
注文送信
注文の作成は、 create_order 関数を使用してください。
from binance.enums import *
order = client.create_order(
symbol='BNBBTC',
side=SIDE_BUY,
type=ORDER_TYPE_LIMIT,
timeInForce=TIME_IN_FORCE_GTC,
quantity=100,
price='0.00001')
指値注文の送信
指値買いまたは売りの注文をするにはヘルパー関数を使用してください。
order = client.order_limit_buy(
symbol='BNBBTC',
quantity=100,
price='0.00001')
order = client.order_limit_sell(
symbol='BNBBTC',
quantity=100,
price='0.00001')
成行注文
成行買いまたは売りの注文をするにはヘルパー関数を使用してください。
order = client.order_market_buy(
symbol='BNBBTC',
quantity=100)
order = client.order_market_sell(
symbol='BNBBTC',
quantity=100)
テスト注文の送信¶
新規注文を作成し、バリデートしますが、取引所には送信しません。
from binance.enums import *
order = client.create_test_order(
symbol='BNBBTC',
side=SIDE_BUY,
type=ORDER_TYPE_LIMIT,
timeInForce=TIME_IN_FORCE_GTC,
quantity=100,
price='0.00001')
全てのオープン注文の取得¶
orders = client.get_open_orders(symbol='BNBBTC')
ウェブソケット¶
ソケットはソケットマネージャーにより処理されます。 BinanceSocketManager
マネージャーを通して複数のソケット接続をすることができます。
それぞれのソケットタイプで一つだけインスタンスが作成されます。例えば、一つのBNBBTC Depth socketを作成し、これはBNBBTC DepthとBNBBTC Tradeの両方のソケットとして同時に使用できます。
ソケット接続を作成すると、コールバック関数はメッセージを受信します。
メッセージはディクショナリーオブジェクトとして受信されます。フォーマットは、 Binance WebSocket API documentation を参照してください。
ウェブソケットは最大5回まで再接続にリトライする設定をすることができます。
ウェブソケットの使用方法¶
マネージャーを作成し、API clientを渡します。
from binance.websockets import BinanceSocketManager
bm = BinanceSocketManager(client)
# 任意のソケットを開始 例)trade socket
conn_key = bm.start_trade_socket('BNBBTC', process_message)
# ソケットマネージャーを開始
bm.start()
メッセージを処理するコールバック
def process_message(msg):
print("message type: {}".format(msg['e']))
print(msg)
# 処理を記述
ウェブソケットエラー¶
ウェブソケットが切断され、再接続ができなかった場合、このことを知らせるメッセージがコールバックに送られます。このフォーマットは下記の通りです。
{
'e': 'error',
'm': 'Max reconnect retries reached'
}
# メッセージの確認
def process_message(msg):
if msg['e'] == 'error':
# 閉じるかソケットを再スタートする処理
else:
# 通常のメッセージ処理
マルチプレックスソケット¶
複数のストリームを合わせたソケットを作成します。
これらのストリームには、depth, kline, ticker, tradeを含めることができます。ただし、ユーザーストリームは別の認証が必要なため、含めることはできません。
ソケット名に使用するSymbolは、小文字でなければなりません。 例)bnbbtc@aggTrade, neobtc@ticker
ソケット名についての詳細は、 Binance Websocket Streams API documentation を参照してください。
def process_m_message(msg):
print("stream: {} data: {}".format(msg['stream'], msg['data']))
# ストリーム名のリストを渡す
conn_key = bm.start_multiplex_socket(['bnbbtc@aggTrade', 'neobtc@ticker'], process_m_message)
Depth Socket¶
デプスソケットには、diff responseではなく、partial bookを受信するためのオプションのデプスパラメーターがあります。 デフォルトではdiff responseが返されます。 有効なデプス値は、5, 10, 20と 列挙型で定義 されている値です。
# depth diff response
diff_key = bm.start_depth_socket('BNBBTC', process_message)
# partial book response
partial_key = bm.start_depth_socket('BNBBTC', process_message, depth=BinanceSocketManager.WEBSOCKET_DEPTH_5)
Kline Socket¶
Klineソケットには、オプションのインターバルパラメータがあります。デフォルトでは1 minuteに設定されています。 有効なインターバル値については、 列挙型定義 を参照してください。
from binance.enums import *
conn_key = bm.start_kline_socket('BNBBTC', process_message, interval=KLINE_INTERVAL_30MINUTE)
Aggregated Trade Socket¶
conn_key = bm.start_aggtrade_socket('BNBBTC', process_message)
Trade Socket¶
conn_key = bm.start_trade_socket('BNBBTC', process_message)
Symbol Ticker Socket¶
conn_key = bm.start_symbol_ticker_socket('BNBBTC', process_message)
Ticker Socket¶
conn_key = bm.start_ticker_socket(process_message)
User Socket¶
これは、3つの異なったユーザーイベントを監視します。
- Account Update Event
- Order Update Event
- Trade Update Event
マネージャーはソケットが接続され続けるようにします。
bm.start_user_socket(process_message)
ソケットの停止¶
個別のソケットを停止するには、 stop_socket 関数を呼びます。 この関数は開始時にリターンされるconn_key parameterを使用します。
bm.stop_socket(conn_key)
全てのソケットを停止し、マネージャーを終了するには、 close を使用します。その後に新しいソケットに接続するには、 start を使用する必要があります。
bm.close()
停止とプログラムの終了¶
ウェブソケットはTwistedライブラリからのリアクターループを使用します。上記の close メソッドを使用するとウェブソケット接続を停止しますが、リアクターループは停止しません。コードは意図したタイミングで終了しないかもしれません。
終了させたい場合、下記のようにリアクターの stop メソッドを使用します。
from twisted.internet import reactor
# プログラムコード
# 終了時
reactor.stop()
Depth Cache デプスキャッシュ¶
通貨ペアのデプスキャッシュの更新をフォローするには、 DepthCacheManager を使用してください。
マネージャーを作成し、api client, symbol(通貨ペア)とオプションのコールバック関数を渡してください。
from binance.depthcache import DepthCacheManager
dcm = DepthCacheManager(client, 'BNBBTC', callback=process_depth)
コールバック関数は、事前にソートしたbidとaskのリストを含み、フィルタリングも可能な現在の DepthCache オブジェクトを受信します。
同じコールバックを使用する複数のキャッシュがある場合は、 depth_cache オブジェクトからsymbolの値にアクセスしてください。
デフォルトでは、デプスキャッシュはRESTリクエストを使用して30分ごとにオーダーブックを取得します。 この間隔は、 refresh_interval で変更することができます。停止させる場合は、0またはNoneを設定してください。 ソケット接続は、フルオーダーブックの受信以降、更新を受信するため常にオープンとなります。
Websocketエラー¶
websocketが切断され、再接続ができない場合、depth_cacheパラメータにはNoneが返されます。
例¶
# 1時間ごとの更新
dcm = DepthCacheManager(client, 'BNBBTC', callback=process_depth, refresh_interval=60*60)
# 更新を無効にする
dcm = DepthCacheManager(client, 'BNBBTC', callback=process_depth, refresh_interval=0)
def process_depth(depth_cache):
if depth_cache is not None:
print("symbol {}".format(depth_cache.symbol))
print("top 5 bids")
print(depth_cache.get_bids()[:5])
print("top 5 asks")
print(depth_cache.get_asks()[:5])
else:
# depth cacheにエラーが発生したため、再スタートが必要
いつでも現在の DepthCache オブジェクトを DepthCacheManager から取得することができます。
depth_cache = dcm.get_depth_cache()
if depth_cache is not None:
print("symbol {}".format(depth_cache.symbol))
print("top 5 bids")
print(depth_cache.get_bids()[:5])
print("top 5 asks")
print(depth_cache.get_asks()[:5])
else:
# depth cacheにエラーが発生したため、再スタートが必要
DepthCacheManager のメッセージ送信を停止するには、 close メソッドを使用してください。 これは、内部websocketを停止し、 DepthCacheManager は再使用できなくなります。
dcm.close()
出金エンドポイント¶
出金処理¶
この呼び出しをするには、APIキーに対してWithdrawal permissions(出金許可)を許可する必要があります。
APIを使用して引き出すには、以前にウェブサイトから出金したことがあり、その登録Eメールを使用してAPIで引き出す許可を与える必要があります。
出金に失敗すると、 BinanceWithdrawException が発生します。
from binance.exceptions import BinanceAPIException, BinanceWithdrawException
try:
# ネームパラメータを渡していない場合は、クライアントからアセットバリューに渡される
result = client.withdraw(
asset='ETH',
address='<eth_address>',
amount=100)
except BinanceAPIException as e:
print(e)
except BinanceWithdrawException as e:
print(e)
else:
print("Success")
# ネームパラメータを渡す
result = client.withdraw(
asset='ETH',
address='<eth_address>',
amount=100,
name='Withdraw')
# XRPやXMRのように、コインが追加のタグまたは名前を必要とする場合、`addressTag`を渡す
result = client.withdraw(
asset='XRP',
address='<xrp_address>',
addressTag='<xrp_address_tag>',
amount=10000)
デポジットの履歴を取得¶
deposits = client.get_deposit_history()
btc_deposits = client.get_deposit_history(asset='BTC')
出金の履歴を渡す¶
withdraws = client.get_withdraw_history()
btc_withdraws = client.get_withdraw_history(asset='BTC')
デポジットアドレスを取得¶
address = client.get_deposit_address(asset='BTC')
ヘルパー関数¶
例外¶
BinanceResponseException¶
JSONレスポンス以外が返された時に発生
BinanceAPIException¶
APIコールエラーの際に、binance.exceptions.BinanceAPIExceptionが発生します。
例外時は、下記の項目にアクセスできます。
- status_code - レスポンスステータスコード
- response - レスポンスオブジェクト
- code - Binanceエラーコード
- message - Binanceエラーメッセージ
- request - ある場合はリクエストオブジェクト
try:
client.get_all_orders()
except BinanceAPIException as e:
print e.status_code
print e.message
BinanceOrderException¶
注文を送信する際、 Binance Trading Rules にパラメータが適合するか確認するため、バリデートされます。
下記の例外は、 BinanceOrderException を継承します。
BinanceOrderMinAmountException¶
指定されたamountがtrade minimum amountの倍数ではない時に発生。
BinanceOrderMinPriceException¶
priceがtrade minimum priceよりも小さい時に発生。
BinanceOrderTotalPriceException¶
totalがtrade minimum totalよりも小さい時に発生。
BinanceOrderUnknownSymbolException¶
適合するsymbolが存在しない時に発生。
BinanceOrderInactiveSymbolException¶
symbolがアクティブではない時に発生。
BinanceWithdrawException¶
出金に失敗した時に発生。
よくある質問¶
Q: なぜ、」Timestamp for this request is not valid」となったのでしょうか?
A: 2つのケースで発生する場合があります。
送信したtimestampが、serverTime - recvWindow valueの範囲外の時。 送信したtimestampが、サーバータイムより1000ms以上早い時。
あなたのシステムの時間が正しいか確認してください。 issue を参照し、ローカルタイムとBinanceサーバータイムの差をチェックするサンプルコードを確認してください。
Q: なぜ」Signature for this request is not valid」となったのでしょうか?
A1: パラメータが正しいフォーマットではない可能性があります。
recvWindowがstringではなくintegerであることを確認してください。
A2: API KeyとSecretを再生成する必要があるかもしれません。
A3: 中国のIPアドレスからBinanceへアクセスしようとしている可能性があります。これは現在、Binanceより禁止されています。
Q: WindowsでTwistedをpipを使用してインストールできません。
A: Twistedのビルド中にエラーが発生する場合、Microsoft Visual C++が必要となります。 Python Wiki on Widows Compilers を参照し、あなたのシステムに対応する正しいバージョンのVisual C++ Build Toolsをインストールしてください。
Changelog¶
v0.6.0 - 2018-01-09¶
New version because why not.
Added
- get_historical_klines function to fetch klines for any date range
- ability to override requests parameters globally
- error on websocket disconnect
- example related to blog post
Fixes
- documentation fixes
v0.5.17 - 2018-01-08¶
Added
- check for name parameter in withdraw, set to asset parameter if not passed
Update
- Windows install error documentation
Removed
- reference to disable_validation in documentation
v0.5.16 - 2018-01-06¶
Added
- addressTag documentation to withdraw function
- documentation about requests proxy environment variables
Update
- FAQ for signature error with solution to regenerate API key
- change create_order to create_test_order in example
Fixed
- reference to BinanceAPIException in documentation
v0.5.14 - 2018-01-02¶
Added
- Wait for depth cache socket to start
- check for sequential depth cache messages
Updated
- documentation around depth websocket and diff and partial responses
Removed
- Removed unused WEBSOCKET_DEPTH_1 enum
- removed unused libraries and imports
v0.5.12 - 2017-12-29¶
Added
- get_asset_balance helper function to fetch an individual asset’s balance
Fixed
- added timeout to requests call to prevent hanging
- changed variable type to str for price parameter when creating an order
- documentation fixes
v0.5.11 - 2017-12-28¶
Added
- refresh interval parameter to depth cache to keep it fresh, set default at 30 minutes
Fixed
- watch depth cache socket before fetching order book to replay any messages
v0.5.10 - 2017-12-28¶
Updated
- updated dependencies certifi and cryptography to help resolve signature error
v0.5.9 - 2017-12-26¶
Fixed
- fixed websocket reconnecting, was no distinction between manual close or network error
v0.5.8 - 2017-12-25¶
Changed
- change symbol parameter to optional for get_open_orders function
- added listenKey parameter to stream_close function
Added
- get_account_status function that was missed
v0.5.7 - 2017-12-24¶
Changed
- change depth cache callback parameter to optional
Added
- note about stopping Twisted reactor loop to exit program
v0.5.6 - 2017-12-20¶
Added
- get_symbol_info function to simplify getting info about a particular symbol
v0.5.4 - 2017-12-14¶
Added
- symbol property made public on DepthCache class
Changed
- Enums now also accessible from binance.client.Client and binance.websockets.BinanceSocketManager
v0.5.3 - 2017-12-09¶
Changed
- User stream refresh timeout from 50 minutes to 30 minutes
- User stream socket listen key change check simplified
v0.5.2 - 2017-12-08¶
Added
- start_multiplex_socket function to BinanceSocketManager to create multiplexed streams
v0.5.1 - 2017-12-06¶
Added
- Close method for DepthCacheManager
Fixes
- Fixed modifying array error message when closing the BinanceSocketManager
v0.5.0 - 2017-12-05¶
Updating to match new API documentation
Added
- Recent trades endpoint
- Historical trades endpoint
- Order response type option
- Check for invalid user stream listen key in socket to keep connected
Fixes
- Fixed exchange info endpoint as it was renamed slightly
v0.4.3 - 2017-12-04¶
Fixes
- Fixed stopping sockets where they were reconnecting
- Fixed websockets unable to be restarted after close
- Exception in parsing non-JSON websocket message
v0.4.0 - 2017-11-19¶
Added
- Get deposit address endpoint
- Upgraded withdraw endpoints to v3
- New exchange info endpoint with rate limits and full symbol info
Removed
- Order validation to return at a later date
v0.3.8 - 2017-11-17¶
Fixes
- Fix order validation for market orders
- WEBSOCKET_DEPTH_20 value, 20 instead of 5
- General tidy up
v0.3.7 - 2017-11-16¶
Fixes
- Fix multiple depth caches sharing a cache by initialising bid and ask objects each time
v0.3.5 - 2017-11-06¶
Added
- support for BNB market
Fixes
- fixed error if new market type is created that we don’t know about
v0.3.4 - 2017-10-31¶
Added
- depth parameter to depth socket
- interval parameter to kline socket
- update time parameter for compatible sockets
- new enums for socket depth and update time values
- better websocket documentation
Changed
- Depth Cache Manager uses 0ms socket update time
- connection key returned when creating socket, this key is then used to stop it
Fixes
- General fixes
v0.3.1 - 2017-10-29¶
Added
- Withdraw exception handler with translation of obscure error
Fixes
- Validation fixes
v0.1.5 - 2017-09-12¶
Changes
- Added get_all_tickers call
- Added get_orderbook_tickers call
- Added some FAQs
Fixes
- Fix error in enum value
v0.1.2 - 2017-08-25¶
Added
- Travis.CI and Coveralls support
Changes
- Validation for pairs using public endpoint
v0.1.0 - 2017-08-16¶
Websocket release
Added
- Websocket manager
- Order parameter validation
- Order and Symbol enums
- API Endpoints for Data Streams
Binance API¶
client module¶
-
class
binance.client.
Client
(api_key, api_secret, requests_params=None)[ソース]¶ ベースクラス:
object
-
API_URL
= 'https://api.binance.com/api'¶
-
KLINE_INTERVAL_12HOUR
= '12h'¶
-
KLINE_INTERVAL_15MINUTE
= '15m'¶
-
KLINE_INTERVAL_1DAY
= '1d'¶
-
KLINE_INTERVAL_1HOUR
= '1h'¶
-
KLINE_INTERVAL_1MINUTE
= '1m'¶
-
KLINE_INTERVAL_1MONTH
= '1M'¶
-
KLINE_INTERVAL_1WEEK
= '1w'¶
-
KLINE_INTERVAL_2HOUR
= '2h'¶
-
KLINE_INTERVAL_30MINUTE
= '30m'¶
-
KLINE_INTERVAL_3DAY
= '3d'¶
-
KLINE_INTERVAL_3MINUTE
= '3m'¶
-
KLINE_INTERVAL_4HOUR
= '4h'¶
-
KLINE_INTERVAL_5MINUTE
= '5m'¶
-
KLINE_INTERVAL_6HOUR
= '6h'¶
-
KLINE_INTERVAL_8HOUR
= '8h'¶
-
ORDER_RESP_TYPE_ACK
= 'ACK'¶
-
ORDER_RESP_TYPE_FULL
= 'FULL'¶
-
ORDER_RESP_TYPE_RESULT
= 'RESULT'¶
-
ORDER_STATUS_CANCELED
= 'CANCELED'¶
-
ORDER_STATUS_EXPIRED
= 'EXPIRED'¶
-
ORDER_STATUS_FILLED
= 'FILLED'¶
-
ORDER_STATUS_NEW
= 'NEW'¶
-
ORDER_STATUS_PARTIALLY_FILLED
= 'PARTIALLY_FILLED'¶
-
ORDER_STATUS_PENDING_CANCEL
= 'PENDING_CANCEL'¶
-
ORDER_STATUS_REJECTED
= 'REJECTED'¶
-
ORDER_TYPE_LIMIT
= 'LIMIT'¶
-
ORDER_TYPE_LIMIT_MAKER
= 'LIMIT_MAKER'¶
-
ORDER_TYPE_MARKET
= 'MARKET'¶
-
ORDER_TYPE_STOP_LOSS
= 'STOP_LOSS'¶
-
ORDER_TYPE_STOP_LOSS_LIMIT
= 'STOP_LOSS_LIMIT'¶
-
ORDER_TYPE_TAKE_PROFIT
= 'TAKE_PROFIT'¶
-
ORDER_TYPE_TAKE_PROFIT_LIMIT
= 'TAKE_PROFIT_LIMIT'¶
-
PRIVATE_API_VERSION
= 'v3'¶
-
PUBLIC_API_VERSION
= 'v1'¶
-
SIDE_BUY
= 'BUY'¶
-
SIDE_SELL
= 'SELL'¶
-
SYMBOL_TYPE_SPOT
= 'SPOT'¶
-
TIME_IN_FORCE_FOK
= 'FOK'¶
-
TIME_IN_FORCE_GTC
= 'GTC'¶
-
TIME_IN_FORCE_IOC
= 'IOC'¶
-
WEBSITE_URL
= 'https://www.binance.com'¶
-
WITHDRAW_API_URL
= 'https://api.binance.com/wapi'¶
-
WITHDRAW_API_VERSION
= 'v3'¶
-
__init__
(api_key, api_secret, requests_params=None)[ソース]¶ Binance API Client constructor
パラメータ: - api_key (str.) – Api Key
- api_secret (str.) – Api Secret
- requests_params (dict.) – optional - Dictionary of requests params to use for all calls
-
cancel_order
(**params)[ソース]¶ Cancel an active order. Either orderId or origClientOrderId must be sent.
パラメータ: - symbol (str) – required
- orderId (int) – The unique order id
- origClientOrderId (str) – optional
- newClientOrderId (str) – Used to uniquely identify this cancel. Automatically generated by default.
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
{ "symbol": "LTCBTC", "origClientOrderId": "myOrder1", "orderId": 1, "clientOrderId": "cancelMyOrder1" }
Raises: BinanceResponseException, BinanceAPIException
-
create_order
(**params)[ソース]¶ Send in a new order
Any order with an icebergQty MUST have timeInForce set to GTC.
パラメータ: - symbol (str) – required
- side (enum) – required
- type (enum) – required
- timeInForce (enum) – required if limit order
- quantity (decimal) – required
- price (str) – required
- newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
- icebergQty (decimal) – Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
- newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
Response ACK:
{ "symbol":"LTCBTC", "orderId": 1, "clientOrderId": "myOrder1" # Will be newClientOrderId "transactTime": 1499827319559 }
Response RESULT:
{ "symbol": "BTCUSDT", "orderId": 28, "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", "transactTime": 1507725176595, "price": "0.00000000", "origQty": "10.00000000", "executedQty": "10.00000000", "status": "FILLED", "timeInForce": "GTC", "type": "MARKET", "side": "SELL" }
Response FULL:
{ "symbol": "BTCUSDT", "orderId": 28, "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", "transactTime": 1507725176595, "price": "0.00000000", "origQty": "10.00000000", "executedQty": "10.00000000", "status": "FILLED", "timeInForce": "GTC", "type": "MARKET", "side": "SELL", "fills": [ { "price": "4000.00000000", "qty": "1.00000000", "commission": "4.00000000", "commissionAsset": "USDT" }, { "price": "3999.00000000", "qty": "5.00000000", "commission": "19.99500000", "commissionAsset": "USDT" }, { "price": "3998.00000000", "qty": "2.00000000", "commission": "7.99600000", "commissionAsset": "USDT" }, { "price": "3997.00000000", "qty": "1.00000000", "commission": "3.99700000", "commissionAsset": "USDT" }, { "price": "3995.00000000", "qty": "1.00000000", "commission": "3.99500000", "commissionAsset": "USDT" } ] }
Raises: BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
-
create_test_order
(**params)[ソース]¶ Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine.
パラメータ: - symbol (str) – required
- side (enum) – required
- type (enum) – required
- timeInForce (enum) – required if limit order
- quantity (decimal) – required
- price (str) – required
- newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
- icebergQty (decimal) – Used with iceberg orders
- newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
- recvWindow (int) – The number of milliseconds the request is valid for
戻り値: API response
{}
Raises: BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
-
get_account
(**params)[ソース]¶ Get current account information.
パラメータ: recvWindow (int) – the number of milliseconds the request is valid for 戻り値: API response { "makerCommission": 15, "takerCommission": 15, "buyerCommission": 0, "sellerCommission": 0, "canTrade": true, "canWithdraw": true, "canDeposit": true, "balances": [ { "asset": "BTC", "free": "4723846.89208129", "locked": "0.00000000" }, { "asset": "LTC", "free": "4763368.68006011", "locked": "0.00000000" } ] }
Raises: BinanceResponseException, BinanceAPIException
-
get_account_status
(**params)[ソース]¶ Get account status detail.
パラメータ: recvWindow (int) – the number of milliseconds the request is valid for 戻り値: API response { "msg": "Order failed:Low Order fill rate! Will be reactivated after 5 minutes.", "success": true, "objs": [ "5" ] }
Raises: BinanceWithdrawException
-
get_aggregate_trades
(**params)[ソース]¶ Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.
パラメータ: - symbol (str) – required
- fromId (str) – ID to get aggregate trades from INCLUSIVE.
- startTime (int) – Timestamp in ms to get aggregate trades from INCLUSIVE.
- endTime (int) – Timestamp in ms to get aggregate trades until INCLUSIVE.
- limit (int) – Default 500; max 500.
戻り値: API response
[ { "a": 26129, # Aggregate tradeId "p": "0.01633102", # Price "q": "4.70443515", # Quantity "f": 27781, # First tradeId "l": 27781, # Last tradeId "T": 1498793709153, # Timestamp "m": true, # Was the buyer the maker? "M": true # Was the trade the best price match? } ]
Raises: BinanceResponseException, BinanceAPIException
-
get_all_orders
(**params)[ソース]¶ Get all account orders; active, canceled, or filled.
パラメータ: - symbol (str) – required
- orderId (int) – The unique order id
- limit (int) – Default 500; max 500.
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
[ { "symbol": "LTCBTC", "orderId": 1, "clientOrderId": "myOrder1", "price": "0.1", "origQty": "1.0", "executedQty": "0.0", "status": "NEW", "timeInForce": "GTC", "type": "LIMIT", "side": "BUY", "stopPrice": "0.0", "icebergQty": "0.0", "time": 1499827319559 } ]
Raises: BinanceResponseException, BinanceAPIException
-
get_all_tickers
()[ソース]¶ Latest price for all symbols.
https://www.binance.com/restapipub.html#symbols-price-ticker
戻り値: List of market tickers [ { "symbol": "LTCBTC", "price": "4.00000200" }, { "symbol": "ETHBTC", "price": "0.07946600" } ]
Raises: BinanceResponseException, BinanceAPIException
-
get_asset_balance
(asset, **params)[ソース]¶ Get current asset balance.
パラメータ: - asset (str) – required
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: dictionary or None if not found
{ "asset": "BTC", "free": "4723846.89208129", "locked": "0.00000000" }
Raises: BinanceResponseException, BinanceAPIException
-
get_deposit_address
(**params)[ソース]¶ Fetch a deposit address for a symbol
https://www.binance.com/restapipub.html
パラメータ: - asset (str) – required
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
{ "address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b", "success": true, "addressTag": "1231212", "asset": "BNB" }
Raises: BinanceResponseException, BinanceAPIException
-
get_deposit_history
(**params)[ソース]¶ Fetch deposit history.
https://www.binance.com/restapipub.html
パラメータ: - asset (str) – optional
- startTime (long) – optional
- endTime (long) – optional
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
{ "depositList": [ { "insertTime": 1508198532000, "amount": 0.04670582, "asset": "ETH", "status": 1 } ], "success": true }
Raises: BinanceResponseException, BinanceAPIException
-
get_exchange_info
()[ソース]¶ Return rate limits and list of symbols
戻り値: list - List of product dictionaries { "timezone": "UTC", "serverTime": 1508631584636, "rateLimits": [ { "rateLimitType": "REQUESTS", "interval": "MINUTE", "limit": 1200 }, { "rateLimitType": "ORDERS", "interval": "SECOND", "limit": 10 }, { "rateLimitType": "ORDERS", "interval": "DAY", "limit": 100000 } ], "exchangeFilters": [], "symbols": [ { "symbol": "ETHBTC", "status": "TRADING", "baseAsset": "ETH", "baseAssetPrecision": 8, "quoteAsset": "BTC", "quotePrecision": 8, "orderTypes": ["LIMIT", "MARKET"], "icebergAllowed": false, "filters": [ { "filterType": "PRICE_FILTER", "minPrice": "0.00000100", "maxPrice": "100000.00000000", "tickSize": "0.00000100" }, { "filterType": "LOT_SIZE", "minQty": "0.00100000", "maxQty": "100000.00000000", "stepSize": "0.00100000" }, { "filterType": "MIN_NOTIONAL", "minNotional": "0.00100000" } ] } ] }
Raises: BinanceResponseException, BinanceAPIException
-
get_historical_klines
(symbol, interval, start_str, end_str=None)[ソース]¶ Get Historical Klines from Binance
See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/
If using offset strings for dates add 「UTC」 to date string e.g. 「now UTC」, 「11 hours ago UTC」
パラメータ: - symbol (str) – Name of symbol pair e.g BNBBTC
- interval (str) – Biannce Kline interval
- start_str (str) – Start date string in UTC format
- end_str (str) – optional - end date string in UTC format
戻り値: list of OHLCV values
-
get_historical_trades
(**params)[ソース]¶ Get older trades.
パラメータ: - symbol (str) – required
- limit (int) – Default 500; max 500.
- fromId (str) – TradeId to fetch from. Default gets most recent trades.
戻り値: API response
[ { "id": 28457, "price": "4.00000100", "qty": "12.00000000", "time": 1499865549590, "isBuyerMaker": true, "isBestMatch": true } ]
Raises: BinanceResponseException, BinanceAPIException
-
get_klines
(**params)[ソース]¶ Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.
パラメータ: - symbol (str) – required
- interval (enum) –
- limit (int) –
- Default 500; max 500.
- startTime (int) –
- endTime (int) –
戻り値: API response
[ [ 1499040000000, # Open time "0.01634790", # Open "0.80000000", # High "0.01575800", # Low "0.01577100", # Close "148976.11427815", # Volume 1499644799999, # Close time "2434.19055334", # Quote asset volume 308, # Number of trades "1756.87402397", # Taker buy base asset volume "28.46694368", # Taker buy quote asset volume "17928899.62484339" # Can be ignored ] ]
Raises: BinanceResponseException, BinanceAPIException
-
get_my_trades
(**params)[ソース]¶ Get trades for a specific symbol.
パラメータ: - symbol (str) – required
- limit (int) – Default 500; max 500.
- fromId (int) – TradeId to fetch from. Default gets most recent trades.
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
[ { "id": 28457, "price": "4.00000100", "qty": "12.00000000", "commission": "10.10000000", "commissionAsset": "BNB", "time": 1499865549590, "isBuyer": true, "isMaker": false, "isBestMatch": true } ]
Raises: BinanceResponseException, BinanceAPIException
-
get_open_orders
(**params)[ソース]¶ Get all open orders on a symbol.
パラメータ: - symbol (str) – optional
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
[ { "symbol": "LTCBTC", "orderId": 1, "clientOrderId": "myOrder1", "price": "0.1", "origQty": "1.0", "executedQty": "0.0", "status": "NEW", "timeInForce": "GTC", "type": "LIMIT", "side": "BUY", "stopPrice": "0.0", "icebergQty": "0.0", "time": 1499827319559 } ]
Raises: BinanceResponseException, BinanceAPIException
-
get_order
(**params)[ソース]¶ Check an order’s status. Either orderId or origClientOrderId must be sent.
パラメータ: - symbol (str) – required
- orderId (int) – The unique order id
- origClientOrderId (str) – optional
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
{ "symbol": "LTCBTC", "orderId": 1, "clientOrderId": "myOrder1", "price": "0.1", "origQty": "1.0", "executedQty": "0.0", "status": "NEW", "timeInForce": "GTC", "type": "LIMIT", "side": "BUY", "stopPrice": "0.0", "icebergQty": "0.0", "time": 1499827319559 }
Raises: BinanceResponseException, BinanceAPIException
-
get_order_book
(**params)[ソース]¶ Get the Order Book for the market
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#order-book
パラメータ: - symbol (str) – required
- limit (int) – Default 100; max 100
戻り値: API response
{ "lastUpdateId": 1027024, "bids": [ [ "4.00000000", # PRICE "431.00000000", # QTY [] # Can be ignored ] ], "asks": [ [ "4.00000200", "12.00000000", [] ] ] }
Raises: BinanceResponseException, BinanceAPIException
-
get_orderbook_ticker
(**params)[ソース]¶ Latest price for a symbol or symbols.
パラメータ: symbol (str) – 戻り値: API response { "symbol": "LTCBTC", "bidPrice": "4.00000000", "bidQty": "431.00000000", "askPrice": "4.00000200", "askQty": "9.00000000" }
OR
[ { "symbol": "LTCBTC", "bidPrice": "4.00000000", "bidQty": "431.00000000", "askPrice": "4.00000200", "askQty": "9.00000000" }, { "symbol": "ETHBTC", "bidPrice": "0.07946700", "bidQty": "9.00000000", "askPrice": "100000.00000000", "askQty": "1000.00000000" } ]
Raises: BinanceResponseException, BinanceAPIException
-
get_orderbook_tickers
()[ソース]¶ Best price/qty on the order book for all symbols.
https://www.binance.com/restapipub.html#symbols-order-book-ticker
戻り値: List of order book market entries [ { "symbol": "LTCBTC", "bidPrice": "4.00000000", "bidQty": "431.00000000", "askPrice": "4.00000200", "askQty": "9.00000000" }, { "symbol": "ETHBTC", "bidPrice": "0.07946700", "bidQty": "9.00000000", "askPrice": "100000.00000000", "askQty": "1000.00000000" } ]
Raises: BinanceResponseException, BinanceAPIException
-
get_products
()[ソース]¶ Return list of products currently listed on Binance
Use get_exchange_info() call instead
戻り値: list - List of product dictionaries Raises: BinanceResponseException, BinanceAPIException
-
get_recent_trades
(**params)[ソース]¶ Get recent trades (up to last 500).
パラメータ: - symbol (str) – required
- limit (int) – Default 500; max 500.
戻り値: API response
[ { "id": 28457, "price": "4.00000100", "qty": "12.00000000", "time": 1499865549590, "isBuyerMaker": true, "isBestMatch": true } ]
Raises: BinanceResponseException, BinanceAPIException
-
get_server_time
()[ソース]¶ Test connectivity to the Rest API and get the current server time.
戻り値: Current server time { "serverTime": 1499827319559 }
Raises: BinanceResponseException, BinanceAPIException
-
get_symbol_info
(symbol)[ソース]¶ Return information about a symbol
パラメータ: symbol (str) – required e.g BNBBTC 戻り値: Dict if found, None if not { "symbol": "ETHBTC", "status": "TRADING", "baseAsset": "ETH", "baseAssetPrecision": 8, "quoteAsset": "BTC", "quotePrecision": 8, "orderTypes": ["LIMIT", "MARKET"], "icebergAllowed": false, "filters": [ { "filterType": "PRICE_FILTER", "minPrice": "0.00000100", "maxPrice": "100000.00000000", "tickSize": "0.00000100" }, { "filterType": "LOT_SIZE", "minQty": "0.00100000", "maxQty": "100000.00000000", "stepSize": "0.00100000" }, { "filterType": "MIN_NOTIONAL", "minNotional": "0.00100000" } ] }
Raises: BinanceResponseException, BinanceAPIException
-
get_symbol_ticker
(**params)[ソース]¶ Latest price for a symbol or symbols.
パラメータ: symbol (str) – 戻り値: API response { "symbol": "LTCBTC", "price": "4.00000200" }
OR
[ { "symbol": "LTCBTC", "price": "4.00000200" }, { "symbol": "ETHBTC", "price": "0.07946600" } ]
Raises: BinanceResponseException, BinanceAPIException
-
get_ticker
(**params)[ソース]¶ 24 hour price change statistics.
パラメータ: symbol (str) – 戻り値: API response { "priceChange": "-94.99999800", "priceChangePercent": "-95.960", "weightedAvgPrice": "0.29628482", "prevClosePrice": "0.10002000", "lastPrice": "4.00000200", "bidPrice": "4.00000000", "askPrice": "4.00000200", "openPrice": "99.00000000", "highPrice": "100.00000000", "lowPrice": "0.10000000", "volume": "8913.30000000", "openTime": 1499783499040, "closeTime": 1499869899040, "fristId": 28385, # First tradeId "lastId": 28460, # Last tradeId "count": 76 # Trade count }
OR
[ { "priceChange": "-94.99999800", "priceChangePercent": "-95.960", "weightedAvgPrice": "0.29628482", "prevClosePrice": "0.10002000", "lastPrice": "4.00000200", "bidPrice": "4.00000000", "askPrice": "4.00000200", "openPrice": "99.00000000", "highPrice": "100.00000000", "lowPrice": "0.10000000", "volume": "8913.30000000", "openTime": 1499783499040, "closeTime": 1499869899040, "fristId": 28385, # First tradeId "lastId": 28460, # Last tradeId "count": 76 # Trade count } ]
Raises: BinanceResponseException, BinanceAPIException
-
get_withdraw_history
(**params)[ソース]¶ Fetch withdraw history.
https://www.binance.com/restapipub.html
パラメータ: - asset (str) – optional
- startTime (long) – optional
- endTime (long) – optional
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
{ "withdrawList": [ { "amount": 1, "address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b", "asset": "ETH", "applyTime": 1508198532000 "status": 4 }, { "amount": 0.005, "address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b", "txId": "0x80aaabed54bdab3f6de5868f89929a2371ad21d666f20f7393d1a3389fad95a1", "asset": "ETH", "applyTime": 1508198532000, "status": 4 } ], "success": true }
Raises: BinanceResponseException, BinanceAPIException
-
order_limit
(timeInForce='GTC', **params)[ソース]¶ Send in a new limit order
Any order with an icebergQty MUST have timeInForce set to GTC.
パラメータ: - symbol (str) – required
- side (enum) – required
- quantity (decimal) – required
- price (str) – required
- timeInForce (enum) – default Good till cancelled
- newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
- icebergQty (decimal) – Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
- newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
See order endpoint for full response options
Raises: BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
-
order_limit_buy
(timeInForce='GTC', **params)[ソース]¶ Send in a new limit buy order
Any order with an icebergQty MUST have timeInForce set to GTC.
パラメータ: - symbol (str) – required
- quantity (decimal) – required
- price (str) – required
- timeInForce (enum) – default Good till cancelled
- newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
- stopPrice (decimal) – Used with stop orders
- icebergQty (decimal) – Used with iceberg orders
- newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
See order endpoint for full response options
Raises: BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
-
order_limit_sell
(timeInForce='GTC', **params)[ソース]¶ Send in a new limit sell order
パラメータ: - symbol (str) – required
- quantity (decimal) – required
- price (str) – required
- timeInForce (enum) – default Good till cancelled
- newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
- stopPrice (decimal) – Used with stop orders
- icebergQty (decimal) – Used with iceberg orders
- newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
See order endpoint for full response options
Raises: BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
-
order_market
(**params)[ソース]¶ Send in a new market order
パラメータ: - symbol (str) – required
- side (enum) – required
- quantity (decimal) – required
- newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
- newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
See order endpoint for full response options
Raises: BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
-
order_market_buy
(**params)[ソース]¶ Send in a new market buy order
パラメータ: - symbol (str) – required
- quantity (decimal) – required
- newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
- newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
See order endpoint for full response options
Raises: BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
-
order_market_sell
(**params)[ソース]¶ Send in a new market sell order
パラメータ: - symbol (str) – required
- quantity (decimal) – required
- newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
- newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
See order endpoint for full response options
Raises: BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
-
ping
()[ソース]¶ Test connectivity to the Rest API.
戻り値: Empty array {}
Raises: BinanceResponseException, BinanceAPIException
-
stream_close
(listenKey)[ソース]¶ Close out a user data stream.
パラメータ: listenKey (str) – required 戻り値: API response {}
Raises: BinanceResponseException, BinanceAPIException
-
stream_get_listen_key
()[ソース]¶ Start a new user data stream and return the listen key If a stream already exists it should return the same key. If the stream becomes invalid a new key is returned.
Can be used to keep the user stream alive.
戻り値: API response { "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" }
Raises: BinanceResponseException, BinanceAPIException
-
stream_keepalive
(listenKey)[ソース]¶ PING a user data stream to prevent a time out.
パラメータ: listenKey (str) – required 戻り値: API response {}
Raises: BinanceResponseException, BinanceAPIException
-
withdraw
(**params)[ソース]¶ Submit a withdraw request.
https://www.binance.com/restapipub.html
Assumptions:
- You must have Withdraw permissions enabled on your API key
- You must have withdrawn to the address specified through the website and approved the transaction via email
パラメータ: - asset (str) – required
- amount (decimal) – required
- name (str) – optional - Description of the address, default asset value passed will be used
- recvWindow (int) – the number of milliseconds the request is valid for
戻り値: API response
{ "msg": "success", "success": true, "id":"7213fea8e94b4a5593d507237e5a555b" }
Raises: BinanceResponseException, BinanceAPIException, BinanceWithdrawException
-
depthcache module¶
-
class
binance.depthcache.
DepthCache
(symbol)[ソース]¶ ベースクラス:
object
-
__init__
(symbol)[ソース]¶ Intialise the DepthCache
パラメータ: symbol (string) – Symbol to create depth cache for
-
get_asks
()[ソース]¶ Get the current asks
戻り値: list of asks with price and quantity as floats [ [ 0.0001955, # Price 57.0' # Quantity ], [ 0.00019699, 778.0 ], [ 0.000197, 64.0 ], [ 0.00019709, 1130.0 ], [ 0.0001971, 385.0 ] ]
-
-
class
binance.depthcache.
DepthCacheManager
(client, symbol, callback=None, refresh_interval=1800)[ソース]¶ ベースクラス:
object
-
__init__
(client, symbol, callback=None, refresh_interval=1800)[ソース]¶ Initialise the DepthCacheManager
パラメータ: - client (binance.Client) – Binance API client
- symbol (string) – Symbol to create depth cache for
- callback (function) – Optional function to receive depth cache updates
- refresh_interval (int) – Optional number of seconds between cache refresh, use 0 or None to disable
-
exceptions module¶
-
exception
binance.exceptions.
BinanceAPIException
(response)[ソース]¶ ベースクラス:
exceptions.Exception
-
LISTENKEY_NOT_EXIST
= '-1125'¶
-
-
exception
binance.exceptions.
BinanceOrderException
(code, message)[ソース]¶ ベースクラス:
exceptions.Exception
helpers module¶
-
binance.helpers.
date_to_milliseconds
(date_str)[ソース]¶ Convert UTC date to milliseconds
If using offset strings add 「UTC」 to date string e.g. 「now UTC」, 「11 hours ago UTC」
See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/
パラメータ: date_str (str) – date in readable format, i.e. 「January 01, 2018」, 「11 hours ago UTC」, 「now UTC」
-
binance.helpers.
interval_to_milliseconds
(interval)[ソース]¶ Convert a Binance interval string to milliseconds
パラメータ: interval (str) – Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w 戻り値: None if unit not one of m, h, d or w None if string not in correct format int value of interval in milliseconds
websockets module¶
-
class
binance.websockets.
BinanceClientFactory
(*args, **kwargs)[ソース]¶ ベースクラス:
autobahn.twisted.websocket.WebSocketClientFactory
,binance.websockets.BinanceReconnectingClientFactory
-
protocol
¶ BinanceClientProtocol
のエイリアス
-
-
class
binance.websockets.
BinanceClientProtocol
[ソース]¶ ベースクラス:
autobahn.twisted.websocket.WebSocketClientProtocol
-
class
binance.websockets.
BinanceReconnectingClientFactory
[ソース]¶ ベースクラス:
twisted.internet.protocol.ReconnectingClientFactory
-
initialDelay
= 0.1¶
-
maxDelay
= 10¶
-
maxRetries
= 5¶
-
-
class
binance.websockets.
BinanceSocketManager
(client)[ソース]¶ ベースクラス:
threading.Thread
-
STREAM_URL
= 'wss://stream.binance.com:9443/'¶
-
WEBSOCKET_DEPTH_10
= '10'¶
-
WEBSOCKET_DEPTH_20
= '20'¶
-
WEBSOCKET_DEPTH_5
= '5'¶
-
__init__
(client)[ソース]¶ Initialise the BinanceSocketManager
パラメータ: client (binance.Client) – Binance API client
-
start_aggtrade_socket
(symbol, callback)[ソース]¶ Start a websocket for symbol trade data
パラメータ: - symbol (str) – required
- callback (function) – callback function to handle messages
戻り値: connection key string if successful, False otherwise
Message Format
{ "e": "aggTrade", # event type "E": 1499405254326, # event time "s": "ETHBTC", # symbol "a": 70232, # aggregated tradeid "p": "0.10281118", # price "q": "8.15632997", # quantity "f": 77489, # first breakdown trade id "l": 77489, # last breakdown trade id "T": 1499405254324, # trade time "m": false, # whether buyer is a maker "M": true # can be ignored }
-
start_depth_socket
(symbol, callback, depth=None)[ソース]¶ Start a websocket for symbol market depth returning either a diff or a partial book
パラメータ: - symbol (str) – required
- callback (function) – callback function to handle messages
- depth (enum) – optional Number of depth entries to return, default None. If passed returns a partial book instead of a diff
戻り値: connection key string if successful, False otherwise
Partial Message Format
{ "lastUpdateId": 160, # Last update ID "bids": [ # Bids to be updated [ "0.0024", # price level to be updated "10", # quantity [] # ignore ] ], "asks": [ # Asks to be updated [ "0.0026", # price level to be updated "100", # quantity [] # ignore ] ] }
Diff Message Format
{ "e": "depthUpdate", # Event type "E": 123456789, # Event time "s": "BNBBTC", # Symbol "U": 157, # First update ID in event "u": 160, # Final update ID in event "b": [ # Bids to be updated [ "0.0024", # price level to be updated "10", # quantity [] # ignore ] ], "a": [ # Asks to be updated [ "0.0026", # price level to be updated "100", # quantity [] # ignore ] ] }
-
start_kline_socket
(symbol, callback, interval='1m')[ソース]¶ Start a websocket for symbol kline data
パラメータ: - symbol (str) – required
- callback (function) – callback function to handle messages
- interval (enum) – Kline interval, default KLINE_INTERVAL_1MINUTE
戻り値: connection key string if successful, False otherwise
Message Format
{ "e": "kline", # event type "E": 1499404907056, # event time "s": "ETHBTC", # symbol "k": { "t": 1499404860000, # start time of this bar "T": 1499404919999, # end time of this bar "s": "ETHBTC", # symbol "i": "1m", # interval "f": 77462, # first trade id "L": 77465, # last trade id "o": "0.10278577", # open "c": "0.10278645", # close "h": "0.10278712", # high "l": "0.10278518", # low "v": "17.47929838", # volume "n": 4, # number of trades "x": false, # whether this bar is final "q": "1.79662878", # quote volume "V": "2.34879839", # volume of active buy "Q": "0.24142166", # quote volume of active buy "B": "13279784.01349473" # can be ignored } }
-
start_multiplex_socket
(streams, callback)[ソース]¶ Start a multiplexed socket using a list of socket names. User stream sockets can not be included.
Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker
Combined stream events are wrapped as follows: {「stream」:」<streamName>」,」data」:<rawPayload>}
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md
パラメータ: - streams (list) – list of stream names in lower case
- callback (function) – callback function to handle messages
戻り値: connection key string if successful, False otherwise
Message Format - see Binance API docs for all types
-
start_symbol_ticker_socket
(symbol, callback)[ソース]¶ Start a websocket for a symbol’s ticker data
パラメータ: - symbol (str) – required
- callback (function) – callback function to handle messages
戻り値: connection key string if successful, False otherwise
Message Format
{ "e": "24hrTicker", # Event type "E": 123456789, # Event time "s": "BNBBTC", # Symbol "p": "0.0015", # Price change "P": "250.00", # Price change percent "w": "0.0018", # Weighted average price "x": "0.0009", # Previous day's close price "c": "0.0025", # Current day's close price "Q": "10", # Close trade's quantity "b": "0.0024", # Best bid price "B": "10", # Bid bid quantity "a": "0.0026", # Best ask price "A": "100", # Best ask quantity "o": "0.0010", # Open price "h": "0.0025", # High price "l": "0.0010", # Low price "v": "10000", # Total traded base asset volume "q": "18", # Total traded quote asset volume "O": 0, # Statistics open time "C": 86400000, # Statistics close time "F": 0, # First trade ID "L": 18150, # Last trade Id "n": 18151 # Total number of trades }
-
start_ticker_socket
(callback)[ソース]¶ Start a websocket for all ticker data
By default all markets are included in an array.
パラメータ: callback (function) – callback function to handle messages 戻り値: connection key string if successful, False otherwise Message Format
[ { 'F': 278610, 'o': '0.07393000', 's': 'BCCBTC', 'C': 1509622420916, 'b': '0.07800800', 'l': '0.07160300', 'h': '0.08199900', 'L': 287722, 'P': '6.694', 'Q': '0.10000000', 'q': '1202.67106335', 'p': '0.00494900', 'O': 1509536020916, 'a': '0.07887800', 'n': 9113, 'B': '1.00000000', 'c': '0.07887900', 'x': '0.07399600', 'w': '0.07639068', 'A': '2.41900000', 'v': '15743.68900000' } ]
-
start_trade_socket
(symbol, callback)[ソース]¶ Start a websocket for symbol trade data
パラメータ: - symbol (str) – required
- callback (function) – callback function to handle messages
戻り値: connection key string if successful, False otherwise
Message Format
{ "e": "trade", # Event type "E": 123456789, # Event time "s": "BNBBTC", # Symbol "t": 12345, # Trade ID "p": "0.001", # Price "q": "100", # Quantity "b": 88, # Buyer order Id "a": 50, # Seller order Id "T": 123456785, # Trade time "m": true, # Is the buyer the market maker? "M": true # Ignore. }
-
start_user_socket
(callback)[ソース]¶ Start a websocket for user data
https://www.binance.com/restapipub.html#user-wss-endpoint
パラメータ: callback (function) – callback function to handle messages 戻り値: connection key string if successful, False otherwise Message Format - see Binance API docs for all types
-