{"id":13605818,"url":"https://github.com/binance/binance-connector-python","last_synced_at":"2025-05-12T15:25:25.861Z","repository":{"id":39492319,"uuid":"257171886","full_name":"binance/binance-connector-python","owner":"binance","description":"Simple connector to Binance Public API","archived":false,"fork":false,"pushed_at":"2025-01-13T11:38:22.000Z","size":629,"stargazers_count":2271,"open_issues_count":27,"forks_count":552,"subscribers_count":48,"default_branch":"master","last_synced_at":"2025-05-05T09:04:26.541Z","etag":null,"topics":["binance-api","connector","crypto","library","market-data","python","real-time","trading"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/binance.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2020-04-20T04:33:46.000Z","updated_at":"2025-05-05T05:47:15.000Z","dependencies_parsed_at":"2023-02-10T13:15:25.894Z","dependency_job_id":"4c4252e2-a82f-4123-b07f-ed1a1e988ac9","html_url":"https://github.com/binance/binance-connector-python","commit_stats":{"total_commits":44,"total_committers":11,"mean_commits":4.0,"dds":0.5227272727272727,"last_synced_commit":"d6546814060fd79ea3ab89d5c64c4696a783e40e"},"previous_names":["binance-exchange/binance-connector-python"],"tags_count":40,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binance%2Fbinance-connector-python","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binance%2Fbinance-connector-python/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binance%2Fbinance-connector-python/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binance%2Fbinance-connector-python/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/binance","download_url":"https://codeload.github.com/binance/binance-connector-python/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253523696,"owners_count":21921815,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["binance-api","connector","crypto","library","market-data","python","real-time","trading"],"created_at":"2024-08-01T19:01:03.150Z","updated_at":"2025-05-12T15:25:25.825Z","avatar_url":"https://github.com/binance.png","language":"Python","readme":"# Binance Public API Connector Python\n[![PyPI version](https://img.shields.io/pypi/v/binance-connector)](https://pypi.python.org/pypi/binance-connector)\n[![Python version](https://img.shields.io/pypi/pyversions/binance-connector)](https://www.python.org/downloads/)\n[![Documentation](https://img.shields.io/badge/docs-latest-blue)](https://binance-connector.readthedocs.io/en/stable/)\n[![Code Style](https://img.shields.io/badge/code_style-black-black)](https://black.readthedocs.io/en/stable/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nThis is a lightweight library that works as a connector to [Binance public API](https://github.com/binance/binance-spot-api-docs)\n\n- Supported APIs:\n    - `/api/*`\n    - `/sapi/*`\n    - Spot Websocket Market Stream\n    - Spot User Data Stream\n    - Spot WebSocket API\n- Inclusion of test cases and examples\n- Customizable base URL, request timeout and HTTP proxy\n- Response metadata can be displayed\n\n## Installation\n\n```bash\npip install binance-connector\n```\n\n## Documentation\n\n[https://binance-connector.readthedocs.io](https://binance-connector.readthedocs.io)\n\n## RESTful APIs\n\nUsage examples:\n```python\nfrom binance.spot import Spot\n\nclient = Spot()\n\n# Get server timestamp\nprint(client.time())\n# Get klines of BTCUSDT at 1m interval\nprint(client.klines(\"BTCUSDT\", \"1m\"))\n# Get last 10 klines of BNBUSDT at 1h interval\nprint(client.klines(\"BNBUSDT\", \"1h\", limit=10))\n\n# API key/secret are required for user data endpoints\nclient = Spot(api_key='\u003capi_key\u003e', api_secret='\u003capi_secret\u003e')\n\n# Get account and balance information\nprint(client.account())\n\n# Post a new order\nparams = {\n    'symbol': 'BTCUSDT',\n    'side': 'SELL',\n    'type': 'LIMIT',\n    'timeInForce': 'GTC',\n    'quantity': 0.002,\n    'price': 9500\n}\n\nresponse = client.new_order(**params)\nprint(response)\n```\nPlease find `examples` folder to check for more endpoints.\n- In order to set your API and Secret Key for use of the examples, create a file `examples/config.ini` with your keys.\n- Eg:\n    ```ini\n    # examples/config.ini\n    [keys]\n    api_key=abc123456\n    api_secret=cba654321\n    ```\n\n### Authentication\n\nBinance supports HMAC, RSA and ED25519 API authentication.\n\n```python\n\n# HMAC: pass API key and secret\nclient = Client(api_key, api_secret)\nprint(client.account())\n\n# RSA Keys\nclient = Client(api_key=api_key, private_key=private_key)\nprint(client.account())\n\n# ED25519 Keys\napi_key = \"\"\nprivate_key = \"./private_key.pem\"\nprivate_key_pass = \"\u003cpassword_if_applicable\u003e\"\n\nwith open(private_key, 'rb') as f:\n    private_key = f.read()\n\nspot_client = Client(api_key=api_key, private_key=private_key, private_key_pass=private_key_pass)\n\n# Encrypted RSA Key\nclient = Client(api_key=api_key, private_key=private_key, private_key_pass='password')\nprint(client.account())\n```\nPlease find `examples/spot/wallet/account_snapshot.py` for more details on ED25519.\nPlease find `examples/spot/trade/get_account.py` for more details on RSA.\n\n### Testnet\n\n[Spot Testnet](https://testnet.binance.vision/) is available, it can be used to test `/api/*` endpoints.\n\n- `/sapi/*` endpoints are not available.\n- No UI.\n- Steps to setup testnet API key.  [https://dev.binance.vision/t/99](https://dev.binance.vision/t/99)\n\nTo use testnet:\n```python\nfrom binance.spot import Spot as Client\n\nclient = Client(base_url='https://testnet.binance.vision')\nprint(client.time())\n```\n\n### Base URL\n\nIf `base_url` is not provided, it defaults to `api.binance.com`.\u003cbr/\u003e\nIt's recommended to pass in the `base_url` parameter, even in production as Binance provides alternative URLs\nin case of performance issues:\n- `https://api1.binance.com`\n- `https://api2.binance.com`\n- `https://api3.binance.com`\n\n### Optional parameters\n\nPEP8 suggests _lowercase with words separated by underscores_, but for this connector,\nthe methods' optional parameters should follow their exact naming as in the API documentation.\n\n```python\n# Recognised parameter name\nresponse = client.cancel_oco_order('BTCUSDT', orderListId=1)\n\n# Unrecognised parameter name\nresponse = client.cancel_oco_order('BTCUSDT', order_list_id=1)\n```\n\n### RecvWindow parameter\n\nAdditional parameter `recvWindow` is available for endpoints requiring signature.\u003cbr/\u003e\nIt defaults to `5000` (milliseconds) and can be any value lower than `60000`(milliseconds).\nAnything beyond the limit will result in an error response from Binance server.\n\n```python\nfrom binance.spot import Spot as Client\n\nclient = Client(api_key, api_secret)\nresponse = client.get_order('BTCUSDT', orderId=11, recvWindow=10000)\n```\n\n### Timeout\n\n`timeout` is available to be assigned with the number of seconds you find most appropriate to wait for a server response.\u003cbr/\u003e\nPlease remember the value as it won't be shown in error message _no bytes have been received on the underlying socket for timeout seconds_.\u003cbr/\u003e\nBy default, `timeout` is None. Hence, requests do not time out.\n\n```python\nfrom binance.spot import Spot as Client\n\nclient= Client(timeout=1)\n```\n\n### Time Unit\n\nThe `time_unit` parameter is optional and allows you to retrieve data with timestamps in `microsecond` or `millisecond`. Users can set it with the following values:\n- `microsecond`\n- `millisecond`\n- `MICROSECOND`\n- `MILLISECOND`\n\nBy default, `time_unit` is set to `None` and will return a timestamp values in milliseconds.\n\n```python\nfrom binance.spot import Spot as Client\n\nclient = Client(time_unit=\"microsecond\")\n```\n\n### Proxy\n\nProxy is supported.\n\n```python\nfrom binance.spot import Spot as Client\n\nproxies = { 'https': 'http://1.2.3.4:8080' }\n\nclient= Client(proxies=proxies)\n```\n\n\n### Response Metadata\n\nThe Binance API server provides weight usages in the headers of each response.\nYou can display them by initializing the client with `show_limit_usage=True`:\n\n```python\nfrom binance.spot import Spot as Client\n\nclient = Client(show_limit_usage=True)\nprint(client.time())\n```\nreturns:\n\n```python\n{'data': {'serverTime': 1587990847650}, 'limit_usage': {'x-mbx-used-weight': '31', 'x-mbx-used-weight-1m': '31'}}\n```\nYou can also display full response metadata to help in debugging:\n\n```python\nclient = Client(show_header=True)\nprint(client.time())\n```\n\nreturns:\n\n```python\n{'data': {'serverTime': 1587990847650}, 'header': {'Context-Type': 'application/json;charset=utf-8', ...}}\n```\n\nIf `ClientError` is received, it'll display full response meta information.\n\n### Display logs\n\nSetting the log level to `DEBUG` will log the request URL, payload and response text.\n\n### Error\n\nThere are 2 types of error returned from the library:\n- `binance.error.ClientError`\n    - This is thrown when server returns `4XX`, it's an issue from client side.\n    - It has 5 properties:\n        - `status_code` - HTTP status code\n        - `error_code` - Server's error code, e.g. `-1102`\n        - `error_message` - Server's error message, e.g. `Unknown order sent.`\n        - `header` - Full response header.\n        - `error_data`* - Additional detailed data which supplements the `error_message`.\n            - **Only applicable on select endpoints, eg. `cancelReplace`*\n- `binance.error.ServerError`\n    - This is thrown when server returns `5XX`, it's an issue from server side.\n\n## Websocket\n\n### Connector v3\n\nWebSocket can be established through either of the following types of connections:\n- WebSocket API (`https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-api.md`)\n- WebSocket Stream (`https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md`)\n\n```python\n\n# WebSocket API Client\nfrom binance.websocket.spot.websocket_api import SpotWebsocketAPIClient\n\ndef message_handler(_, message):\n    logging.info(message)\n\nmy_client = SpotWebsocketAPIClient(on_message=message_handler)\n\nmy_client.ticker(symbol=\"BNBBUSD\", type=\"FULL\")\n\ntime.sleep(5)\nlogging.info(\"closing ws connection\")\nmy_client.stop()\n```\n\n```python\n\n# WebSocket Stream Client\nfrom binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient\n\ndef message_handler(_, message):\n    logging.info(message)\n\nmy_client = SpotWebsocketStreamClient(on_message=message_handler)\n\n# Subscribe to a single symbol stream\nmy_client.agg_trade(symbol=\"bnbusdt\")\ntime.sleep(5)\nlogging.info(\"closing ws connection\")\nmy_client.stop()\n```\n\n### Time Unit\n\nThe `time_unit` parameter is optional and allows you to retrieve data with timestamps in `microsecond` or `millisecond`. Users can set it with the following values:\n- `microsecond`\n- `millisecond`\n- `MICROSECOND`\n- `MILLISECOND`\n\nBy default, `time_unit` is set to `None` and will return a timestamp values in milliseconds.\n\n```python\n# WebSocket API Client\nimport logging\nfrom binance.websocket.spot.websocket_api import SpotWebsocketAPIClient\n\ndef message_handler(_, message):\n    logging.info(message)\n\n\nmy_client = SpotWebsocketAPIClient(on_message=message_handler, time_unit='microsecond')\n```\n\n```python\n# WebSocket Stream Client\nimport logging\nfrom binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient\n\ndef message_handler(_, message):\n    logging.info(message)\n\nmy_client = SpotWebsocketStreamClient(on_message=message_handler, time_unit=\"microsecond\")\n```\n\n#### Proxy\n\nProxy is supported for both WebSocket API and WebSocket Stream.\n\nTo use it, pass in the `proxies` parameter when initializing the client.\n\nThe format of the `proxies` parameter is the same as the one used in the Spot RESTful API.\n\nIt consists on a dictionary with the following format, where the key is the type of the proxy and the value is the proxy URL:\n\nFor websockets, the proxy type is `http`.\n\n```python\nproxies = { 'http': 'http://1.2.3.4:8080' }\n```\n\nYou can also use authentication for the proxy by adding the `username` and `password` parameters to the proxy URL:\n\n```python\nproxies = { 'http': 'http://username:password@host:port' }\n```\n\n\n```python\n\n# WebSocket API Client\nfrom binance.websocket.spot.websocket_api import SpotWebsocketAPIClient\n\ndef message_handler(_, message):\n    logging.info(message)\n\nproxies = { 'http': 'http://1.2.3.4:8080' }\n\nmy_client = SpotWebsocketAPIClient(on_message=message_handler, proxies=proxies, timeout=10)\n\nmy_client.ticker(symbol=\"BNBBUSD\", type=\"FULL\")\n\ntime.sleep(5)\nlogging.info(\"closing ws connection\")\nmy_client.stop()\n```\n\n```python\n\n# WebSocket Stream Client\nfrom binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient\n\ndef message_handler(_, message):\n    logging.info(message)\n\nproxies = { 'http': 'http://1.2.3.4:8080' }\n\nmy_client = SpotWebsocketStreamClient(on_message=message_handler, proxies=proxies, timeout=10)\n\n# Subscribe to a single symbol stream\nmy_client.agg_trade(symbol=\"bnbusdt\")\ntime.sleep(5)\nlogging.info(\"closing ws connection\")\nmy_client.stop()\n```\n\n#### Request Id\n\nClient 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.\n\n```python\n# id provided by client\nmy_client.ping_connectivity(id=\"my_request_id\")\n\n# library will generate a random uuid string\nmy_client.ping_connectivity()\n```\n\n#### Combined Streams\n- If you set `is_combined` to `True`, `\"/stream/\"` will be appended to the `baseURL` to allow for Combining streams.\n- `is_combined` defaults to `False` and `\"/ws/\"` (raw streams) will be appended to the `baseURL`.\n\nMore websocket examples are available in the `examples` folder.\n\nExample file \"examples/websocket_api/app_demo.py\" demonstrates how Websocket API and Websocket Stream can be used together.\n\n### Connector v1 and v2\n\n```python\nfrom binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient\n\ndef message_handler(message):\n    print(message)\n\nws_client = WebsocketClient()\nws_client.start()\n\nws_client.mini_ticker(\n    symbol='bnbusdt',\n    id=1,\n    callback=message_handler,\n)\n\n# Combine selected streams\nws_client.instant_subscribe(\n    stream=['bnbusdt@bookTicker', 'ethusdt@bookTicker'],\n    callback=message_handler,\n)\n\nws_client.stop()\n```\n\n### Heartbeat\n\nOnce connected, the websocket server sends a ping frame every 3 minutes and requires a response pong frame back within\na 10 minutes period. This package handles the pong responses automatically.\n\n### Testnet\n\n```python\nfrom binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient\n\nws_client = WebsocketClient(stream_url='wss://stream.testnet.binance.vision')\n```\n\n## Test Case\n\n```python\n# In case packages are not installed yet\npip install -r requirements/requirements-test.txt\n\npython -m pytest tests/\n```\n\n## Limitation\n\nFutures and Vanilla Options APIs are not supported:\n  - `/fapi/*`\n  - `/dapi/*`\n  - `/vapi/*`\n  -  Associated Websocket Market and User Data Streams\n\n## Contributing\n\nContributions are welcome.\u003cbr/\u003e\nIf you've found a bug within this project, please open an issue to discuss what you would like to change.\u003cbr/\u003e\nIf it's an issue with the API, please open a topic at [Binance Developer Community](https://dev.binance.vision)\n","funding_links":[],"categories":["Python","Curated List"],"sub_categories":["API Integrations/Connectors"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinance%2Fbinance-connector-python","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbinance%2Fbinance-connector-python","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinance%2Fbinance-connector-python/lists"}