This is an unofficial Python wrapper for the Binance exchange REST API v3. I am in no way affiliated with Binance, use at your own risk.
python-binance
latest
GettingStarted
BinanceConstants
GeneralEndpoints
MarketDataEndpoints
AccountEndpoints
SubAccountEndpoints
MarginTradingEndpoints
Websockets
DepthCache
WithdrawEndpoints
HelperFunctions
Exceptions
FAQ
Changelog
BinanceAPI
python-binance
Docs»
Welcometopython-binancev1.0.16
EditonGitHub
Welcometopython-binancev1.0.16¶
Updated9thApr2022
ThisisanunofficialPythonwrapperfortheBinanceexchangeRESTAPIv3.IaminnowayaffiliatedwithBinance,useatyourownrisk.
IfyoucameherelookingfortheBinanceexchangetopurchasecryptocurrencies,thengohere.
IfyouwanttoautomateinteractionswithBinancestickaround.
Ifyou’reinterestedinBinance’snewDEXBinanceChainseemypython-binance-chainlibrary
Sourcecode
https://github.com/sammchardy/python-binance
Documentation
https://python-binance.readthedocs.io/en/latest/
BinanceAPITelegram
https://t.me/binance_api_english
Blogwithexamplesincludingasync
https://sammchardy.github.io
AsyncbasicsforBinance
UnderstandingBinanceOrderFilters
MakesureyouupdateoftenandchecktheChangelogfornewfeaturesandbugfixes.
Features¶
ImplementationofallGeneral,MarketDataandAccountendpoints.
Asyncioimplementation
TestnetsupportforSpot,FuturesandVanillaOptions
Simplehandlingofauthentication
Noneedtogeneratetimestampsyourself,thewrapperdoesitforyou
Responseexceptionhandling
Websockethandlingwithreconnectionandmultiplexedconnections
SymbolDepthCache
HistoricalKline/Candlefetchingfunction
Withdrawfunctionality
Depositaddresses
MarginTrading
FuturesTrading
VanillaOptions
Supportotherdomains(.us,.jp,etc)
Upgradingtov1.0.0+¶
Thebreakingchangesincludethemigrationfromwapitosapiendpointswhichrelatedtothe
walletendpointsdetailedintheBinanceDocs
TheotherbreakingchangeisforwebsocketstreamsandtheDepthCacheManagerwhichhavebeen
convertedtouseAsynchronousContextManagers.SeeexamplesintheAsyncsectionbeloworviewthe
websocketsand
depthcachedocs.
QuickStart¶
RegisteranaccountwithBinance.
GenerateanAPIKeyandassignrelevantpermissions.
IfyouareusinganexchangefromtheUS,JapanorotherTLDthenmakesurepasstld=’us’whencreatingthe
client.
TousetheSpotorVanillaOptionsTestnet,
passtestnet=Truewhencreatingtheclient.
pipinstallpython-binance
frombinanceimportClient,ThreadedWebsocketManager,ThreadedDepthCacheManager
client=Client(api_key,api_secret)
#getmarketdepth
depth=client.get_order_book(symbol='BNBBTC')
#placeatestmarketbuyorder,toplaceanactualorderusethecreate_orderfunction
order=client.create_test_order(
symbol='BNBBTC',
side=Client.SIDE_BUY,
type=Client.ORDER_TYPE_MARKET,
quantity=100)
#getallsymbolprices
prices=client.get_all_tickers()
#withdraw100ETH
#checkdocsforassumptionsaroundwithdrawals
frombinance.exceptionsimportBinanceAPIException
try:
result=client.withdraw(
asset='ETH',
address='',
amount=100)
exceptBinanceAPIExceptionase:
print(e)
else:
print("Success")
#fetchlistofwithdrawals
withdraws=client.get_withdraw_history()
#fetchlistofETHwithdrawals
eth_withdraws=client.get_withdraw_history(coin='ETH')
#getadepositaddressforBTC
address=client.get_deposit_address(coin='BTC')
#gethistoricalklinedatafromanydaterange
#fetch1minuteklinesforthelastdayupuntilnow
klines=client.get_historical_klines("BNBBTC",Client.KLINE_INTERVAL_1MINUTE,"1dayagoUTC")
#fetch30minuteklinesforthelastmonthof2017
klines=client.get_historical_klines("ETHBTC",Client.KLINE_INTERVAL_30MINUTE,"1Dec,2017","1Jan,2018")
#fetchweeklyklinessinceitlisted
klines=client.get_historical_klines("NEOBTC",Client.KLINE_INTERVAL_1WEEK,"1Jan,2017")
#socketmanagerusingthreads
twm=ThreadedWebsocketManager()
twm.start()
#depthcachemanagerusingthreads
dcm=ThreadedDepthCacheManager()
dcm.start()
defhandle_socket_message(msg):
print(f"messagetype:{msg['e']}")
print(msg)
defhandle_dcm_message(depth_cache):
print(f"symbol{depth_cache.symbol}")
print("top5bids")
print(depth_cache.get_bids()[:5])
print("top5asks")
print(depth_cache.get_asks()[:5])
print("lastupdatetime{}".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')
#replacewithacurrentoptionssymbol
options_symbol='BTC-210430-36000-C'
dcm.start_options_depth_cache(callback=handle_dcm_message,symbol=options_symbol)
#jointhethreadedmanagerstothemainthread
twm.join()
dcm.join()
Formorecheckoutthedocumentation.
AsyncExample¶
ReadAsyncbasicsforBinance
formoreinformation.
importasyncio
importjson
frombinanceimportAsyncClient,DepthCacheManager,BinanceSocketManager
asyncdefmain():
#initialisetheclient
client=awaitAsyncClient.create()
#runsomesimplerequests
print(json.dumps(awaitclient.get_exchange_info(),indent=2))
print(json.dumps(awaitclient.get_symbol_ticker(symbol="BTCUSDT"),indent=2))
#initialisewebsocketfactorymanager
bsm=BinanceSocketManager(client)
#createlistenerusingasyncwith
#thiswillexitandclosetheconnectionafter5messages
asyncwithbsm.trade_socket('ETHBTC')asts:
for_inrange(5):
res=awaitts.recv()
print(f'recv{res}')
#gethistoricalklinedatafromanydaterange
#fetch1minuteklinesforthelastdayupuntilnow
klines=client.get_historical_klines("BNBBTC",AsyncClient.KLINE_INTERVAL_1MINUTE,"1dayagoUTC")
#usegeneratortofetch1minuteklinesforthelastdayupuntilnow
asyncforklineinawaitclient.get_historical_klines_generator("BNBBTC",AsyncClient.KLINE_INTERVAL_1MINUTE,"1dayagoUTC"):
print(kline)
#fetch30minuteklinesforthelastmonthof2017
klines=client.get_historical_klines("ETHBTC",Client.KLINE_INTERVAL_30MINUTE,"1Dec,2017","1Jan,2018")
#fetchweeklyklinessinceitlisted
klines=client.get_historical_klines("NEOBTC",Client.KLINE_INTERVAL_1WEEK,"1Jan,2017")
#setupanasynccontexttheDepthCacheandexitafter5messages
asyncwithDepthCacheManager(client,symbol='ETHBTC')asdcm_socket:
for_inrange(5):
depth_cache=awaitdcm_socket.recv()
print(f"symbol{depth_cache.symbol}updated:{depth_cache.update_time}")
print("Top5asks:")
print(depth_cache.get_asks()[:5])
print("Top5bids:")
print(depth_cache.get_bids()[:5])
#VanillaoptionsDepthCacheworksthesame,updatethesymboltoacurrentone
options_symbol='BTC-210430-36000-C'
asyncwithOptionsDepthCacheManager(client,symbol=options_symbol)asdcm_socket:
for_inrange(5):
depth_cache=awaitdcm_socket.recv()
count+=1
print(f"symbol{depth_cache.symbol}updated:{depth_cache.update_time}")
print("Top5asks:")
print(depth_cache.get_asks()[:5])
print("Top5bids:")
print(depth_cache.get_bids()[:5])
awaitclient.close_connection()
if__name__=="__main__":
loop=asyncio.get_event_loop()
loop.run_until_complete(main())
Donate¶
Ifthislibraryhelpedyououtfeelfreetodonate.
ETH:0xD7a7fDdCfA687073d7cC93E9E51829a727f9fE70
LTC:LPC5vw9ajR1YndE1hYVeo3kJ9LdHjcRCUZ
NEO:AVJB4ZgN7VgSUtArCt94y7ZYT6d5NDfpBo
BTC:1Dknp6L6oRZrHDECRedihPzx2sSfmvEBys
OtherExchanges¶
IfyouuseBinanceChaincheckoutmypython-binance-chainlibrary.
IfyouuseKucoincheckoutmypython-kucoinlibrary.
IfyouuseIDEXcheckoutmypython-idexlibrary.
Contents¶
GettingStarted
Installation
RegisteronBinance
GenerateanAPIKey
Initialisetheclient
UsingtheSpot,FuturesorVanillaOptionsTestnet
UsingadifferentTLD
MakingAPICalls
AsyncAPICalls
APIRateLimit
RequestsSettings
BinanceConstants
GeneralEndpoints
Pingtheserver
Gettheservertime
Getsystemstatus
GetExchangeInfo
GetSymbolInfo
GetAllCoinsInfo
GetGetDailyAccountSnapshot
GetCurrentProducts
MarketDataEndpoints
GetMarketDepth
GetRecentTrades
GetHistoricalTrades
GetAggregateTrades
AggregateTradeIterator
GetKline/Candlesticks
GetHistoricalKline/Candlesticks
GetHistoricalKline/Candlesticksusingagenerator
Getaveragepriceforasymbol
Get24hrTicker
GetAllPrices
GetOrderbookTickers
AccountEndpoints
Orders
Account
SubAccountEndpoints
GetSubAccountlist
GetSubAccountTransferHistory
GetSubAccountAssets
MarginTradingEndpoints
MarketData
Orders
Account
Trades
Loans
Websockets
ThreadedWebsocketManagerWebsocketUsage
BinanceSocketManagerWebsocketUsage
UsingadifferentTLD
WebsocketErrors
DepthCache
ThreadedDepthCacheManagerWebsocketUsage
DepthCacheManagerorOptionsDepthCacheManagerUsage
ShareaSocketManager
WebsocketErrors
Examples
WithdrawEndpoints
Placeawithdrawal
Fetchdeposithistory
Fetchwithdrawhistory
Getdepositaddress
HelperFunctions
Exceptions
BinanceRequestException
BinanceAPIException
FAQ
Changelog
v1.0.16-2022-04-09
v1.0.15-2021-09-27
v1.0.14-2021-09-08
v1.0.13-2021-09-08
v1.0.12-2021-06-03
v1.0.10-2021-05-13
v1.0.9-2021-05-12
v1.0.8-2021-05-11
v1.0.7
v1.0.6
v1.0.5
v1.0.4
v1.0.3
v1.0.2
v1.0.1
v1.0.0
v0.7.11
v0.7.5.dev
v0.7.5-2020-02-06
v0.7.4-2019-09-22
v0.7.3-2019-08-12
v0.7.2-2019-08-01
v0.7.1-2019-01-23
v0.7.0-2018-08-08
v0.6.9-2018-04-27
v0.6.8-2018-03-29
v0.6.7-2018-03-14
v0.6.6-2018-02-17
v0.6.5-2018-02-13
v0.6.4-2018-02-09
v0.6.3-2018-01-29
v0.6.2-2018-01-12
v0.6.1-2018-01-10
v0.6.0-2018-01-09
v0.5.17-2018-01-08
v0.5.16-2018-01-06
v0.5.15-2018-01-03
v0.5.14-2018-01-02
v0.5.13-2018-01-01
v0.5.12-2017-12-29
v0.5.11-2017-12-28
v0.5.10-2017-12-28
v0.5.9-2017-12-26
v0.5.8-2017-12-25
v0.5.7-2017-12-24
v0.5.6-2017-12-20
v0.5.5-2017-12-19
v0.5.4-2017-12-14
v0.5.3-2017-12-09
v0.5.2-2017-12-08
v0.5.1-2017-12-06
v0.5.0-2017-12-05
v0.4.3-2017-12-04
v0.4.2-2017-11-30
v0.4.1-2017-11-24
v0.4.0-2017-11-19
v0.3.8-2017-11-17
v0.3.7-2017-11-16
v0.3.6-2017-11-15
v0.3.5-2017-11-06
v0.3.4-2017-10-31
v0.3.3-2017-10-31
v0.3.2-2017-10-30
v0.3.1-2017-10-29
v0.3.0-2017-10-29
v0.2.0-2017-10-27
v0.1.6-2017-10-25
v0.1.5-2017-09-12
v0.1.4-2017-09-06
v0.1.3-2017-08-26
v0.1.2-2017-08-25
v0.1.1-2017-08-17
v0.1.0-2017-08-16
v0.0.2-2017-08-14
BinanceAPI
clientmodule
depthcachemodule
exceptionsmodule
helpersmodule
websocketsmodule
Index¶
Index
ReadtheDocs
v:latest
Versions
latest
stable
Downloads
pdf
html
epub
OnReadtheDocs
ProjectHome
Builds
FreedocumenthostingprovidedbyReadtheDocs.