Package: binance-connector-zxw
修复了原版websocket连接丢失错误无法捕获的BUG,其他没变Binance Public API Connector PythonThis is a lightweight library that works as a connector toBinance public APISupported APIs:/api/*/sapi/*Spot Websocket Market StreamSpot User Data StreamSpot WebSocket APIInclusion of test cases and examplesCustomizable base URL, request timeout and HTTP proxyResponse metadata can be displayedInstallationpipinstallbinance-connectorDocumentationhttps://binance-connector.readthedocs.ioRESTful APIsUsage examples:frombinance.spotimportSpotclient=Spot()# Get server timestampprint(client.time())# Get klines of BTCUSDT at 1m intervalprint(client.klines("BTCUSDT","1m"))# Get last 10 klines of BNBUSDT at 1h intervalprint(client.klines("BNBUSDT","1h",limit=10))# API key/secret are required for user data endpointsclient=Spot(api_key='<api_key>',api_secret='<api_secret>')# Get account and balance informationprint(client.account())# Post a new orderparams={'symbol':'BTCUSDT','side':'SELL','type':'LIMIT','timeInForce':'GTC','quantity':0.002,'price':9500}response=client.new_order(**params)print(response)Please findexamplesfolder to check for more endpoints.In order to set your API and Secret Key for use of the examples, create a fileexamples/config.iniwith your keys.Eg:# examples/config.ini[keys]api_key=abc123456api_secret=cba654321AuthenticationBinance supports HMAC, RSA and ED25519 API authentication.# HMAC: pass API key and secretclient=Client(api_key,api_secret)print(client.account())# RSA Keysclient=Client(api_key=api_key,private_key=private_key)print(client.account())# ED25519 Keysapi_key=""private_key="./private_key.pem"private_key_pass="<password_if_applicable>"withopen(private_key,'rb')asf:private_key=f.read()spot_client=Client(api_key=api_key,private_key=private_key,private_key_pass=private_key_pass)# Encrypted RSA Keyclient=Client(api_key=api_key,private_key=private_key,private_key_pass='password')print(client.account())Please findexamples/spot/wallet/account_snapshot.pyfor more details on ED25519.
Please findexamples/spot/trade/get_account.pyfor more details on RSA.TestnetSpot Testnetis available, it can be used to test/api/*endpoints./sapi/*endpoints are not available.No UI.Steps to setup testnet API key.https://dev.binance.vision/t/99To use testnet:frombinance.spotimportSpotasClientclient=Client(base_url='https://testnet.binance.vision')print(client.time())Base URLIfbase_urlis not provided, it defaults toapi.binance.com.It's recommended to pass in thebase_urlparameter, even in production as Binance provides alternative URLs
in case of performance issues:https://api1.binance.comhttps://api2.binance.comhttps://api3.binance.comOptional 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.cancel_oco_order('BTCUSDT',orderListId=1)# Unrecognised parameter nameresponse=client.cancel_oco_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.spotimportSpotasClientclient=Client(api_key,api_secret)response=client.get_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.spotimportSpotasClientclient=Client(timeout=1)ProxyProxy is supported.frombinance.spotimportSpotasClientproxies={'https':'http://1.2.3.4:8080'}client=Client(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.spotimportSpotasClientclient=Client(show_limit_usage=True)print(client.time())returns:{'data':{'serverTime':1587990847650},'limit_usage':{'x-mbx-used-weight':'31','x-mbx-used-weight-1m':'31'}}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 5 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.error_data* - Additional detailed data which supplements theerror_message.*Only applicable on select endpoints, eg.cancelReplacebinance.error.ServerErrorThis is thrown when server returns5XX, it's an issue from server side.WebsocketConnector v3WebSocket can be established through either of the following types of connections:WebSocket API (https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-api.md)WebSocket Stream (https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md)# WebSocket API Clientfrombinance.websocket.spot.websocket_apiimportSpotWebsocketAPIClientdefmessage_handler(_,message):logging.info(message)my_client=SpotWebsocketAPIClient(on_message=message_handler)my_client.ticker(symbol="BNBBUSD",type="FULL")time.sleep(5)logging.info("closing ws connection")my_client.stop()# WebSocket Stream Clientfrombinance.websocket.spot.websocket_streamimportSpotWebsocketStreamClientdefmessage_handler(_,message):logging.info(message)my_client=SpotWebsocketStreamClient(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()ProxyProxy is supported for both WebSocket API and WebSocket Stream.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 API Clientfrombinance.websocket.spot.websocket_apiimportSpotWebsocketAPIClientdefmessage_handler(_,message):logging.info(message)proxies={'http':'http://1.2.3.4:8080'}my_client=SpotWebsocketAPIClient(on_message=message_handler,proxies=proxies)my_client.ticker(symbol="BNBBUSD",type="FULL")time.sleep(5)logging.info("closing ws connection")my_client.stop()# WebSocket Stream Clientfrombinance.websocket.spot.websocket_streamimportSpotWebsocketStreamClientdefmessage_handler(_,message):logging.info(message)proxies={'http':'http://1.2.3.4:8080'}my_client=SpotWebsocketStreamClient(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()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.ping_connectivity(id="my_request_id")# library will generate a random uuid stringmy_client.ping_connectivity()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 theexamplesfolder.Example file "examples/websocket_api/app_demo.py" demonstrates how Websocket API and Websocket Stream can be used together.Connector v1 and v2frombinance.websocket.spot.websocket_clientimportSpotWebsocketClientasWebsocketClientdefmessage_handler(message):print(message)ws_client=WebsocketClient()ws_client.start()ws_client.mini_ticker(symbol='bnbusdt',id=1,callback=message_handler,)# Combine selected streamsws_client.instant_subscribe(stream=['bnbusdt@bookTicker','ethusdt@bookTicker'],callback=message_handler,)ws_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.Testnetfrombinance.websocket.spot.websocket_clientimportSpotWebsocketClientasWebsocketClientws_client=WebsocketClient(stream_url='wss://testnet.binance.vision')Test Case# In case packages are not installed yetpipinstall-rrequirements/requirements-test.txtpytestLimitationFutures and Vanilla Options APIs are not supported:/fapi/*/dapi/*/vapi/*Associated Websocket Market and User Data StreamsContributingContributions are welcome.If you've found a bug within this project, please open an issue to discuss what you would like to change.If it's an issue with the API, please open a topic atBinance Developer Community