Package: binance-futures-connector
Binance Futures Public API Connector PythonThis is a lightweight library that works as a connector toBinance Futures public APISupported APIs:USDT-M Futures/fapi/*COIN-M Delivery/dapi/*Futures/Delivery Websocket Market StreamFutures/Delivery User Data StreamInclusion of examplesCustomizable base URL, request timeoutResponse metadata can be displayedInstallationpipinstallbinance-futures-connectorRESTful APIsUsage examples:frombinance.cm_futuresimportCMFuturescm_futures_client=CMFutures()# get server timeprint(cm_futures_client.time())cm_futures_client=CMFutures(key='<api_key>',secret='<api_secret>')# Get account informationprint(cm_futures_client.account())# Post a new orderparams={'symbol':'BTCUSDT','side':'SELL','type':'LIMIT','timeInForce':'GTC','quantity':0.002,'price':59808}response=cm_futures_client.new_order(**params)print(response)Please findexamplesfolder to check for more endpoints.AuthenticationBinance supports HMAC and RSA API authentication.# HMAC Authenticationclient=Client(api_key,api_secret)print(client.account())# RSA Authenticationkey=""withopen("/Users/john/private_key.pem","r")asf:# Location of private key fileprivate_key=f.read()private_key_passphrase=""# Optional: only used for encrypted RSA keyclient=Client(key=key,private_key=private_key,private_key_passphrase=private_key_passphrase)print(client.account())Please seeexamples/um_futures/trade/get_account.pyorexamples/cm_futures/trade/get_account.pyfor more details.Base URLFor USDT-M Futures, ifbase_urlis not provided, it defaults tofapi.binance.com.For COIN-M Delivery, ifbase_urlis not provided, it defaults todapi.binance.com.It's recommended to pass in thebase_urlparameter, even in production as Binance provides alternative URLsOptional parametersPEP8 suggestslowercase with words separated by underscores, but for this connector,
the methods' optional parameters should follow their exact naming as in the API documentation.# Recognised parameter nameresponse=client.query_order('BTCUSDT',orderListId=1)# Unrecognised parameter nameresponse=client.query_order('BTCUSDT',order_list_id=1)RecvWindow parameterAdditional parameterrecvWindowis available for endpoints requiring signature.It defaults to5000(milliseconds) and can be any value lower than60000(milliseconds).
Anything beyond the limit will result in an error response from Binance server.frombinance.cm_futuresimportCMFuturescm_futures_client=CMFutures(key='<api_key>',secret='<api_secret>')response=cm_futures_client.query_order('BTCUSDT',orderId=11,recvWindow=10000)Timeouttimeoutis available to be assigned with the number of seconds you find most appropriate to wait for a server response.Please remember the value as it won't be shown in error messageno bytes have been received on the underlying socket for timeout seconds.By default,timeoutis None. Hence, requests do not time out.frombinance.cm_futuresimportCMFuturesclient=CMFutures(timeout=1)Proxyproxy is supportedfrombinance.cm_futuresimportCMFuturesproxies={'https':'http://1.2.3.4:8080'}client=CMFutures(proxies=proxies)Response MetadataThe Binance API server provides weight usages in the headers of each response.
You can display them by initializing the client withshow_limit_usage=True:frombinance.cm_futuresimportCMFuturesclient=CMFutures(show_limit_usage=True)print(client.time())returns:{'limit_usage':{'x-mbx-used-weight-1m':'1'},'data':{'serverTime':1653563092778}}You can also display full response metadata to help in debugging:client=Client(show_header=True)print(client.time())returns:{'data':{'serverTime':1587990847650},'header':{'Context-Type':'application/json;charset=utf-8',...}}IfClientErroris received, it'll display full response meta information.Display logsSetting the log level toDEBUGwill log the request URL, payload and response text.ErrorThere are 2 types of error returned from the library:binance.error.ClientErrorThis is thrown when server returns4XX, it's an issue from client side.It has 4 properties:status_code- HTTP status codeerror_code- Server's error code, e.g.-1102error_message- Server's error message, e.g.Unknown order sent.header- Full response header.binance.error.ServerErrorThis is thrown when server returns5XX, it's an issue from server side.WebsocketConnector v4WebSocket can be established through the following connections:USD-M WebSocket Stream (https://binance-docs.github.io/apidocs/futures/en/#websocket-market-streams)COIN-M WebSocket Stream (https://binance-docs.github.io/apidocs/delivery/en/#websocket-market-streams)# WebSocket Stream Clientimporttimefrombinance.websocket.um_futures.websocket_clientimportUMFuturesWebsocketClientdefmessage_handler(_,message):logging.info(message)my_client=UMFuturesWebsocketClient(on_message=message_handler)# Subscribe to a single symbol streammy_client.agg_trade(symbol="bnbusdt")time.sleep(5)logging.info("closing ws connection")my_client.stop()Request IdClient can assign a request id to each request. The request id will be returned in the response message. Not mandatory in the library, it generates a uuid format string if not provided.# id provided by clientmy_client.agg_trade(symbol="bnbusdt",id="my_request_id")# library will generate a random uuid stringmy_client.agg_trade(symbol="bnbusdt")ProxyProxy is supported for both WebSocket CM futures and UM futures.To use it, pass in theproxiesparameter when initializing the client.The format of theproxiesparameter is the same as the one used in the Spot RESTful API.It consists on a dictionary with the following format, where the key is the type of the proxy and the value is the proxy URL:For websockets, the proxy type ishttp.proxies={'http':'http://1.2.3.4:8080'}You can also use authentication for the proxy by adding theusernameandpasswordparameters to the proxy URL:proxies={'http':'http://username:password@host:port'}# WebSocket Stream Clientimporttimefrombinance.websocket.um_futures.websocket_clientimportUMFuturesWebsocketClientproxies={'http':'http://1.2.3.4:8080'}defmessage_handler(_,message):logging.info(message)my_client=UMFuturesWebsocketClient(on_message=message_handler,proxies=proxies)# Subscribe to a single symbol streammy_client.agg_trade(symbol="bnbusdt")time.sleep(5)logging.info("closing ws connection")my_client.stop()Combined StreamsIf you setis_combinedtoTrue,"/stream/"will be appended to thebaseURLto allow for Combining streams.is_combineddefaults toFalseand"/ws/"(raw streams) will be appended to thebaseURL.More websocket examples are available in theexamplesfolderWebsocket < v4importtimefrombinance.websocket.um_futures.websocket_clientimportUMFuturesWebsocketClientdefmessage_handler(message):print(message)my_client=UMFuturesWebsocketClient(on_message=message_handler)# Subscribe to a single symbol streammy_client.agg_trade(symbol="bnbusdt")time.sleep(5)print("closing ws connection")my_client.stop()HeartbeatOnce connected, the websocket server sends a ping frame every 3 minutes and requires a response pong frame back within
a 10 minutes period. This package handles the pong responses automatically.LicenseMIT