Package: python-binance2
Updated 11th May 2021This is an unofficial Python wrapper for theBinance exchange REST API v3. I am in no way affiliated with Binance, use at your own risk.If you came here looking for theBinance exchangeto purchase cryptocurrencies, thengo here.
If you want to automate interactions with Binance stick around.If you’re interested in Binance’s new DEX Binance Chain see mypython-binance-chain librarySource codehttps://github.com/sammchardy/python-binanceDocumentationhttps://python-binance.readthedocs.io/en/latest/Binance API Telegramhttps://t.me/binance_api_englishBlog with examples including asynchttps://sammchardy.github.ioAsync basics for BinanceUnderstanding Binance Order FiltersMake sure you update often and check theChangelogfor new features and bug fixes.FeaturesImplementation of all General, Market Data and Account endpoints.Asyncio implementationTestnet support for Spot, Futures and Vanilla OptionsSimple handling of authenticationNo need to generate timestamps yourself, the wrapper does it for youResponse exception handlingWebsocket handling with reconnection and multiplexed connectionsSymbol Depth CacheHistorical Kline/Candle fetching functionWithdraw functionalityDeposit addressesMargin TradingFutures TradingVanilla OptionsSupport other domains (.us, .jp, etc)Upgrading to v1.0.0+The breaking changes include the migration from wapi to sapi endpoints which related to the
wallet endpoints detailed in theBinance DocsThe other breaking change is for websocket streams and the Depth Cache Manager which have been
converted to use Asynchronous Context Managers. See examples in the Async section below or view thewebsocketsanddepth cachedocs.Quick StartRegister an account with Binance.Generate an API Keyand assign relevant permissions.If you are using an exchange from the US, Japan or other TLD then make sure passtld=’us’when creating the
client.To use theSpotorVanilla OptionsTestnet,
passtestnet=Truewhen creating the client.pipinstallpython-binancefrombinanceimportClient,ThreadedWebsocketManager,ThreadedDepthCacheManagerclient=Client(api_key,api_secret)# get market depthdepth=client.get_order_book(symbol='BNBBTC')# place a test market buy order, to place an actual order use the create_order functionorder=client.create_test_order(symbol='BNBBTC',side=Client.SIDE_BUY,type=Client.ORDER_TYPE_MARKET,quantity=100)# get all symbol pricesprices=client.get_all_tickers()# withdraw 100 ETH# check docs for assumptions around withdrawalsfrombinance.exceptionsimportBinanceAPIExceptiontry:result=client.withdraw(asset='ETH',address='<eth_address>',amount=100)exceptBinanceAPIExceptionase:print(e)else:print("Success")# fetch list of withdrawalswithdraws=client.get_withdraw_history()# fetch list of ETH withdrawalseth_withdraws=client.get_withdraw_history(coin='ETH')# get a deposit address for BTCaddress=client.get_deposit_address(coin='BTC')# get historical kline data from any date range# fetch 1 minute klines for the last day up until nowklines=client.get_historical_klines("BNBBTC",Client.KLINE_INTERVAL_1MINUTE,"1 day ago UTC")# fetch 30 minute klines for the last month of 2017klines=client.get_historical_klines("ETHBTC",Client.KLINE_INTERVAL_30MINUTE,"1 Dec, 2017","1 Jan, 2018")# fetch weekly klines since it listedklines=client.get_historical_klines("NEOBTC",Client.KLINE_INTERVAL_1WEEK,"1 Jan, 2017")# socket manager using threadstwm=ThreadedWebsocketManager()twm.start()# depth cache manager using threadsdcm=ThreadedDepthCacheManager()dcm.start()defhandle_socket_message(msg):print(f"message type:{msg['e']}")print(msg)defhandle_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 symboloptions_symbol='BTC-210430-36000-C'dcm.start_options_depth_cache(callback=handle_dcm_message,symbol=options_symbol)# join the threaded managers to the main threadtwm.join()dcm.join()For morecheck out the documentation.Async ExampleReadAsync basics for Binancefor more information.importasyncioimportjsonfrombinanceimportAsyncClient,DepthCacheManager,BinanceSocketManagerasyncdefmain():# initialise the clientclient=awaitAsyncClient.create()# run some simple requestsprint(json.dumps(awaitclient.get_exchange_info(),indent=2))print(json.dumps(awaitclient.get_symbol_ticker(symbol="BTCUSDT"),indent=2))# initialise websocket factory managerbsm=BinanceSocketManager(client)# create listener using async with# this will exit and close the connection after 5 messagesasyncwithbsm.trade_socket('ETHBTC')asts:for_inrange(5):res=awaitts.recv()print(f'recv{res}')# get historical kline data from any date range# fetch 1 minute klines for the last day up until nowklines=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 nowasyncforklineinawaitclient.get_historical_klines_generator("BNBBTC",AsyncClient.KLINE_INTERVAL_1MINUTE,"1 day ago UTC"):print(kline)# fetch 30 minute klines for the last month of 2017klines=client.get_historical_klines("ETHBTC",Client.KLINE_INTERVAL_30MINUTE,"1 Dec, 2017","1 Jan, 2018")# fetch weekly klines since it listedklines=client.get_historical_klines("NEOBTC",Client.KLINE_INTERVAL_1WEEK,"1 Jan, 2017")# setup an async context the Depth Cache and exit after 5 messagesasyncwithDepthCacheManager(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("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 oneoptions_symbol='BTC-210430-36000-C'asyncwithOptionsDepthCacheManager(client,symbol=options_symbol)asdcm_socket:for_inrange(5):depth_cache=awaitdcm_socket.recv()count+=1print(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])awaitclient.close_connection()if__name__=="__main__":loop=asyncio.get_event_loop()loop.run_until_complete(main())DonateIf this library helped you out feel free to donate.ETH: 0xD7a7fDdCfA687073d7cC93E9E51829a727f9fE70LTC: LPC5vw9ajR1YndE1hYVeo3kJ9LdHjcRCUZNEO: AVJB4ZgN7VgSUtArCt94y7ZYT6d5NDfpBoBTC: 1Dknp6L6oRZrHDECRedihPzx2sSfmvEBysOther ExchangesIf you useBinance Chaincheck out mypython-binance-chainlibrary.If you useKucoincheck out mypython-kucoinlibrary.If you useIDEXcheck out mypython-idexlibrary.