這是幣安交易所 REST API v3 的非官方 Python 包裝。
如果您來這裡尋找幣安交易所購買加密貨幣,那麼請到這裡。如果您想自動化與幣安的交互,請繼續關注。
該項目由
請確保您的python-binance版本為v.1.0.20或更高版本。不再推薦先前的版本,因為某些端點已被棄用。
確保經常更新並檢查更新日誌以獲取新功能和錯誤修復。
隨時歡迎您的貢獻、建議和修復!請隨時打開 GitHub 問題或透過 Telegram 聊天聯絡我們
重大變更包括從 wapi 到 sapi 端點的遷移,這與幣安文檔中詳細介紹的錢包端點相關
另一個重大變更是針對 websocket 流和深度快取管理器,它們已轉換為使用非同步上下文管理器。請參閱下面的非同步部分中的範例或查看 websockets 和深度快取文件。
在幣安註冊帳戶。
產生API Key並分配相關權限。
如果您使用的是來自美國、日本或其他 TLD 的交易所,請確保在建立用戶端時傳遞 tld='us'。
若要使用現貨、普通選擇權或期貨測試網,請在建立用戶端時傳遞 testnet=True。
pip install python-binance
from binance import Client , ThreadedWebsocketManager , ThreadedDepthCacheManager
client = Client ( api_key , api_secret )
# get market depth
depth = client . get_order_book ( symbol = 'BNBBTC' )
# place a test market buy order, to place an actual order use the create_order function
order = client . create_test_order (
symbol = 'BNBBTC' ,
side = Client . SIDE_BUY ,
type = Client . ORDER_TYPE_MARKET ,
quantity = 100 )
# get all symbol prices
prices = client . get_all_tickers ()
# withdraw 100 ETH
# check docs for assumptions around withdrawals
from binance . exceptions import BinanceAPIException
try :
result = client . withdraw (
asset = 'ETH' ,
address = '' ,
amount = 100 )
except BinanceAPIException as e :
print ( e )
else :
print ( "Success" )
# fetch list of withdrawals
withdraws = client . get_withdraw_history ()
# fetch list of ETH withdrawals
eth_withdraws = client . get_withdraw_history ( coin = 'ETH' )
# get a deposit address for BTC
address = client . get_deposit_address ( coin = 'BTC' )
# get historical kline data from any date range
# fetch 1 minute klines for the last day up until now
klines = client . get_historical_klines ( "BNBBTC" , Client . KLINE_INTERVAL_1MINUTE , "1 day ago UTC" )
# fetch 30 minute klines for the last month of 2017
klines = client . get_historical_klines ( "ETHBTC" , Client . KLINE_INTERVAL_30MINUTE , "1 Dec, 2017" , "1 Jan, 2018" )
# fetch weekly klines since it listed
klines = client . get_historical_klines ( "NEOBTC" , Client . KLINE_INTERVAL_1WEEK , "1 Jan, 2017" )
# create order through websockets
order_ws = client . ws_create_order ( symbol = "LTCUSDT" , side = "BUY" , type = "MARKET" , quantity = 0.1 )
# get account using custom headers
account = client . get_account ( headers = { 'MyCustomKey' : 'MyCustomValue' })
# socket manager using threads
twm = ThreadedWebsocketManager ()
twm . start ()
# depth cache manager using threads
dcm = ThreadedDepthCacheManager ()
dcm . start ()
def handle_socket_message ( msg ):
print ( f"message type: { msg [ 'e' ] } " )
print ( msg )
def handle_dcm_message ( depth_cache ):
print ( f"symbol { depth_cache . symbol } " )
print ( "top 5 bids" )
print ( depth_cache . get_bids ()[: 5 ])
print ( "top 5 asks" )
print ( depth_cache . get_asks ()[: 5 ])
print ( "last update time {}" . format ( depth_cache . update_time ))
twm . start_kline_socket ( callback = handle_socket_message , symbol = 'BNBBTC' )
dcm . start_depth_cache ( callback = handle_dcm_message , symbol = 'ETHBTC' )
# replace with a current options symbol
options_symbol = 'BTC-241227-41000-C'
dcm . start_options_depth_cache ( callback = handle_dcm_message , symbol = options_symbol )
# join the threaded managers to the main thread
twm . join ()
dcm . join ()
有關更多信息,請查看文檔。
閱讀幣安異步基礎知識以了解更多資訊。
import asyncio
import json
from binance import AsyncClient , DepthCacheManager , BinanceSocketManager
async def main ():
# initialise the client
client = await AsyncClient . create ()
# run some simple requests
print ( json . dumps ( await client . get_exchange_info (), indent = 2 ))
print ( json . dumps ( await client . get_symbol_ticker ( symbol = "BTCUSDT" ), indent = 2 ))
# initialise websocket factory manager
bsm = BinanceSocketManager ( client )
# create listener using async with
# this will exit and close the connection after 5 messages
async with bsm . trade_socket ( 'ETHBTC' ) as ts :
for _ in range ( 5 ):
res = await ts . recv ()
print ( f'recv { res } ' )
# get historical kline data from any date range
# fetch 1 minute klines for the last day up until now
klines = client . get_historical_klines ( "BNBBTC" , AsyncClient . KLINE_INTERVAL_1MINUTE , "1 day ago UTC" )
# use generator to fetch 1 minute klines for the last day up until now
async for kline in await client . get_historical_klines_generator ( "BNBBTC" , AsyncClient . KLINE_INTERVAL_1MINUTE , "1 day ago UTC" ):
print ( kline )
# fetch 30 minute klines for the last month of 2017
klines = await client . get_historical_klines ( "ETHBTC" , Client . KLINE_INTERVAL_30MINUTE , "1 Dec, 2017" , "1 Jan, 2018" )
# fetch weekly klines since it listed
klines = await client . get_historical_klines ( "NEOBTC" , Client . KLINE_INTERVAL_1WEEK , "1 Jan, 2017" )
# create order through websockets
order_ws = await client . ws_create_order ( symbol = "LTCUSDT" , side = "BUY" , type = "MARKET" , quantity = 0.1 )
# setup an async context the Depth Cache and exit after 5 messages
async with DepthCacheManager ( client , symbol = 'ETHBTC' ) as dcm_socket :
for _ in range ( 5 ):
depth_cache = await dcm_socket . recv ()
print ( f"symbol { depth_cache . symbol } updated: { depth_cache . update_time } " )
print ( "Top 5 asks:" )
print ( depth_cache . get_asks ()[: 5 ])
print ( "Top 5 bids:" )
print ( depth_cache . get_bids ()[: 5 ])
# Vanilla options Depth Cache works the same, update the symbol to a current one
options_symbol = 'BTC-241227-41000-C'
async with OptionsDepthCacheManager ( client , symbol = options_symbol ) as dcm_socket :
for _ in range ( 5 ):
depth_cache = await dcm_socket . recv ()
count += 1
print ( f"symbol { depth_cache . symbol } updated: { depth_cache . update_time } " )
print ( "Top 5 asks:" )
print ( depth_cache . get_asks ()[: 5 ])
print ( "Top 5 bids:" )
print ( depth_cache . get_bids ()[: 5 ])
await client . close_connection ()
if __name__ == "__main__" :
loop = asyncio . get_event_loop ()
loop . run_until_complete ( main ())
該庫受麻省理工學院許可,這意味著任何開發人員都可以在其之上建立商業和開源軟體,但使用它的風險由您自己承擔,沒有任何保證。
Python-binance 也支援 orjson 來解析 JSON,因為它比內建函式庫快得多。這在使用 websocket 時尤其重要,因為某些交換會傳回需要盡快解析和分派的大消息。
但是,orjson 預設並未啟用,因為並非每個 python 解釋器都支援它。如果您想選擇加入,只需在本機環境中安裝它(pip install 或json)即可。 Python-binance 將檢測安裝並自動選擇它。
業務諮詢:[email protected]