# Binance SDK (Python)
[](https://www.python.org/downloads/)
[](https://sidan-lab.github.io/sidan-binance-py/)
[](https://github.com/astral-sh/ruff)
[](https://opensource.org/licenses/MIT)
> **๐ Fork Notice**: This repository is a significantly modified fork of the official [binance-connector-python](https://github.com/binance/binance-connector-python). It has been refactored to use modern Python packaging (pyproject.toml), updated tooling (uv, ruff), and enhanced development workflows.
**sidan-binance-py** is a lightweight, modern Python library for connecting to the [Binance public API](https://github.com/binance/binance-spot-api-docs). This fork includes significant improvements over the original connector:
## โจ **What's New in This Fork**
- ๐๏ธ **Modern packaging**: Migrated from setup.py to pyproject.toml with uv package manager
- ๐ ๏ธ **Enhanced tooling**: Ruff for linting/formatting, pre-commit hooks, mypy support
- ๐ **Automated docs**: GitHub Actions for documentation deployment
- ๐ **Improved workflows**: Streamlined development and CI/CD processes
- ๐ฆ **Simplified imports**: Import as `binance` (not `binance-connector`)
## ๐ **Supported APIs**
- `/api/*` - Spot trading endpoints
- `/sapi/*` - Binance API endpoints
- Spot Websocket Market Stream
- Spot User Data Stream
- Spot WebSocket API
- Comprehensive test cases and examples
- Customizable base URL, request timeout and HTTP proxy
- Response metadata display
## ๐ฆ **Installation**
### Using pip (recommended)
```bash
pip install sidan-binance-py
```
### Using uv (fastest)
```bash
uv add sidan-binance-py
```
### From source
```bash
git clone https://github.com/sidan-lab/sidan-binance-py.git
cd sidan-binance-py
uv sync
```
## ๐ **Documentation**
- **API Documentation**: [https://sidan-lab.github.io/sidan-binance-py/](https://sidan-lab.github.io/sidan-binance-py/)
- **Original Binance Connector**: [binance-connector.readthedocs.io](https://binance-connector.readthedocs.io)
## ๐ **Key Differences from Original Connector**
| Feature | Original Connector | This Fork (sidan-binance-py) |
| ------------------ | ------------------------------- | --------------------------------- |
| **Package Name** | `binance-connector` | `sidan-binance-py` |
| **Import** | `from binance.spot import Spot` | `from binance.spot import Spot` โ |
| **Packaging** | setup.py | pyproject.toml + uv |
| **Linting** | flake8 + black | ruff (faster, more features) |
| **Pre-commit** | Basic setup | Comprehensive hooks |
| **Documentation** | ReadTheDocs | GitHub Actions + Pages |
| **Type Checking** | None | mypy configured |
| **Python Support** | 3.8+ | 3.8+ (same) |
> **๐ก Import Compatibility**: The import statements remain the same as the original connector, so you can easily switch between packages without changing your code!
## ๐ **Quick Start**
### RESTful APIs
```python
from binance.spot import Spot
client = Spot()
# Get server timestamp
print(client.time())
# Get klines of BTCUSDT at 1m interval
print(client.klines("BTCUSDT", "1m"))
# Get last 10 klines of BNBUSDT at 1h interval
print(client.klines("BNBUSDT", "1h", limit=10))
# API key/secret are required for user data endpoints
client = Spot(api_key='<api_key>', api_secret='<api_secret>')
# Get account and balance information
print(client.account())
# Post a new order
params = {
'symbol': 'BTCUSDT',
'side': 'SELL',
'type': 'LIMIT',
'timeInForce': 'GTC',
'quantity': 0.002,
'price': 9500
}
response = client.new_order(**params)
print(response)
```
Please find `examples` folder to check for more endpoints.
- In order to set your API and Secret Key for use of the examples, create a file `examples/config.ini` with your keys.
- Eg:
```ini
# examples/config.ini
[keys]
api_key=abc123456
api_secret=cba654321
```
### Authentication
Binance supports HMAC, RSA and ED25519 API authentication.
```python
# HMAC: pass API key and secret
client = Client(api_key, api_secret)
print(client.account())
# RSA Keys
client = Client(api_key=api_key, private_key=private_key)
print(client.account())
# ED25519 Keys
api_key = ""
private_key = "./private_key.pem"
private_key_pass = "<password_if_applicable>"
with open(private_key, 'rb') as f:
private_key = f.read()
spot_client = Client(api_key=api_key, private_key=private_key, private_key_pass=private_key_pass)
# Encrypted RSA Key
client = Client(api_key=api_key, private_key=private_key, private_key_pass='password')
print(client.account())
```
Please find `examples/spot/wallet/account_snapshot.py` for more details on ED25519.
Please find `examples/spot/trade/get_account.py` for more details on RSA.
### Testnet
[Spot Testnet](https://testnet.binance.vision/) is 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/99](https://dev.binance.vision/t/99)
To use testnet:
```python
from binance.spot import Spot as Client
client = Client(base_url='https://testnet.binance.vision')
print(client.time())
```
### Base URL
If `base_url` is not provided, it defaults to `api.binance.com`.<br/>
It's recommended to pass in the `base_url` parameter, even in production as Binance provides alternative URLs
in case of performance issues:
- `https://api1.binance.com`
- `https://api2.binance.com`
- `https://api3.binance.com`
### Optional parameters
PEP8 suggests _lowercase with words separated by underscores_, but for this connector,
the methods' optional parameters should follow their exact naming as in the API documentation.
```python
# Recognised parameter name
response = client.cancel_oco_order('BTCUSDT', orderListId=1)
# Unrecognised parameter name
response = client.cancel_oco_order('BTCUSDT', order_list_id=1)
```
### RecvWindow parameter
Additional parameter `recvWindow` is available for endpoints requiring signature.<br/>
It defaults to `5000` (milliseconds) and can be any value lower than `60000`(milliseconds).
Anything beyond the limit will result in an error response from Binance server.
```python
from binance.spot import Spot as Client
client = Client(api_key, api_secret)
response = client.get_order('BTCUSDT', orderId=11, recvWindow=10000)
```
### Timeout
`timeout` is available to be assigned with the number of seconds you find most appropriate to wait for a server response.<br/>
Please remember the value as it won't be shown in error message _no bytes have been received on the underlying socket for timeout seconds_.<br/>
By default, `timeout` is None. Hence, requests do not time out.
```python
from binance.spot import Spot as Client
client= Client(timeout=1)
```
### Time Unit
The `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:
- `microsecond`
- `millisecond`
- `MICROSECOND`
- `MILLISECOND`
By default, `time_unit` is set to `None` and will return a timestamp values in milliseconds.
```python
from binance.spot import Spot as Client
client = Client(time_unit="microsecond")
```
### Proxy
Proxy is supported.
```python
from binance.spot import Spot as Client
proxies = { 'https': 'http://1.2.3.4:8080' }
client= Client(proxies=proxies)
```
### Response Metadata
The Binance API server provides weight usages in the headers of each response.
You can display them by initializing the client with `show_limit_usage=True`:
```python
from binance.spot import Spot as Client
client = Client(show_limit_usage=True)
print(client.time())
```
returns:
```python
{'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:
```python
client = Client(show_header=True)
print(client.time())
```
returns:
```python
{'data': {'serverTime': 1587990847650}, 'header': {'Context-Type': 'application/json;charset=utf-8', ...}}
```
If `ClientError` is received, it'll display full response meta information.
### Display logs
Setting the log level to `DEBUG` will log the request URL, payload and response text.
### Error
There are 2 types of error returned from the library:
- `binance.error.ClientError`
- This is thrown when server returns `4XX`, it's an issue from client side.
- It has 5 properties:
- `status_code` - HTTP status code
- `error_code` - Server's error code, e.g. `-1102`
- `error_message` - Server's error message, e.g. `Unknown order sent.`
- `header` - Full response header.
- `error_data`\* - Additional detailed data which supplements the `error_message`.
- \*_Only applicable on select endpoints, eg. `cancelReplace`_
- `binance.error.ServerError`
- This is thrown when server returns `5XX`, it's an issue from server side.
## Websocket
### Connector v3
WebSocket 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`)
```python
# WebSocket API Client
from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient
def message_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()
```
```python
# WebSocket Stream Client
from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient
def message_handler(_, message):
logging.info(message)
my_client = SpotWebsocketStreamClient(on_message=message_handler)
# Subscribe to a single symbol stream
my_client.agg_trade(symbol="bnbusdt")
time.sleep(5)
logging.info("closing ws connection")
my_client.stop()
```
### Time Unit
The `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:
- `microsecond`
- `millisecond`
- `MICROSECOND`
- `MILLISECOND`
By default, `time_unit` is set to `None` and will return a timestamp values in milliseconds.
```python
# WebSocket API Client
import logging
from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient
def message_handler(_, message):
logging.info(message)
my_client = SpotWebsocketAPIClient(on_message=message_handler, time_unit='microsecond')
```
```python
# WebSocket Stream Client
import logging
from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient
def message_handler(_, message):
logging.info(message)
my_client = SpotWebsocketStreamClient(on_message=message_handler, time_unit="microsecond")
```
#### Proxy
Proxy is supported for both WebSocket API and WebSocket Stream.
To use it, pass in the `proxies` parameter when initializing the client.
The format of the `proxies` parameter 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 is `http`.
```python
proxies = { 'http': 'http://1.2.3.4:8080' }
```
You can also use authentication for the proxy by adding the `username` and `password` parameters to the proxy URL:
```python
proxies = { 'http': 'http://username:password@host:port' }
```
```python
# WebSocket API Client
from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient
def message_handler(_, message):
logging.info(message)
proxies = { 'http': 'http://1.2.3.4:8080' }
my_client = SpotWebsocketAPIClient(on_message=message_handler, proxies=proxies, timeout=10)
my_client.ticker(symbol="BNBBUSD", type="FULL")
time.sleep(5)
logging.info("closing ws connection")
my_client.stop()
```
```python
# WebSocket Stream Client
from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient
def message_handler(_, message):
logging.info(message)
proxies = { 'http': 'http://1.2.3.4:8080' }
my_client = SpotWebsocketStreamClient(on_message=message_handler, proxies=proxies, timeout=10)
# Subscribe to a single symbol stream
my_client.agg_trade(symbol="bnbusdt")
time.sleep(5)
logging.info("closing ws connection")
my_client.stop()
```
#### Request Id
Client 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.
```python
# id provided by client
my_client.ping_connectivity(id="my_request_id")
# library will generate a random uuid string
my_client.ping_connectivity()
```
#### Combined Streams
- If you set `is_combined` to `True`, `"/stream/"` will be appended to the `baseURL` to allow for Combining streams.
- `is_combined` defaults to `False` and `"/ws/"` (raw streams) will be appended to the `baseURL`.
More websocket examples are available in the `examples` folder.
Example file "examples/websocket_api/app_demo.py" demonstrates how Websocket API and Websocket Stream can be used together.
### Connector v1 and v2
```python
from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient
def message_handler(message):
print(message)
ws_client = WebsocketClient()
ws_client.start()
ws_client.mini_ticker(
symbol='bnbusdt',
id=1,
callback=message_handler,
)
# Combine selected streams
ws_client.instant_subscribe(
stream=['bnbusdt@bookTicker', 'ethusdt@bookTicker'],
callback=message_handler,
)
ws_client.stop()
```
### Heartbeat
Once 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.
### Testnet
```python
from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient
ws_client = WebsocketClient(stream_url='wss://stream.testnet.binance.vision')
```
## ๐งช **Development & Testing**
### Running Tests
```bash
# Using the modern uv workflow
make test # Run all tests
make test-smoke # Run smoke tests only
# Or manually with uv
uv run pytest tests/ -q
```
### Code Quality
```bash
make fmt # Format code with ruff
make lint # Lint code with ruff
make precommit # Run all pre-commit hooks
make type # Type check with mypy
```
### Documentation
```bash
make docs-build # Build documentation
make docs-serve # Build and view documentation
```
### Development Setup
```bash
git clone YOUR_REPO_URL
cd sidan-binance-py
make install # Install dependencies
make hooks # Setup pre-commit hooks
```
## Limitation
Futures and Vanilla Options APIs are not supported:
- `/fapi/*`
- `/dapi/*`
- `/vapi/*`
- Associated Websocket Market and User Data Streams
## Contributing
Contributions are welcome.<br/>
If you've found a bug within this project, please open an issue to discuss what you would like to change.<br/>
If it's an issue with the API, please open a topic at [Binance Developer Community](https://dev.binance.vision)
Raw data
{
"_id": null,
"home_page": null,
"name": "sidan-binance-py",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "Binance, Cryptocurrency, Public API, SDK, Trading, WebSocket",
"author": "Binance",
"author_email": "Fork Maintainer <maintainer@example.com>",
"download_url": "https://files.pythonhosted.org/packages/17/ea/04d30a99efd87a92c28bfec35894263564fccdee0fb7941fcccc0265b407/sidan_binance_py-0.0.2.tar.gz",
"platform": null,
"description": "# Binance SDK (Python)\n\n[](https://www.python.org/downloads/)\n[](https://sidan-lab.github.io/sidan-binance-py/)\n[](https://github.com/astral-sh/ruff)\n[](https://opensource.org/licenses/MIT)\n\n> **\ud83d\udd17 Fork Notice**: This repository is a significantly modified fork of the official [binance-connector-python](https://github.com/binance/binance-connector-python). It has been refactored to use modern Python packaging (pyproject.toml), updated tooling (uv, ruff), and enhanced development workflows.\n\n**sidan-binance-py** is a lightweight, modern Python library for connecting to the [Binance public API](https://github.com/binance/binance-spot-api-docs). This fork includes significant improvements over the original connector:\n\n## \u2728 **What's New in This Fork**\n\n- \ud83c\udfd7\ufe0f **Modern packaging**: Migrated from setup.py to pyproject.toml with uv package manager\n- \ud83d\udee0\ufe0f **Enhanced tooling**: Ruff for linting/formatting, pre-commit hooks, mypy support\n- \ud83d\udcda **Automated docs**: GitHub Actions for documentation deployment\n- \ud83d\ude80 **Improved workflows**: Streamlined development and CI/CD processes\n- \ud83d\udce6 **Simplified imports**: Import as `binance` (not `binance-connector`)\n\n## \ud83d\udd0c **Supported APIs**\n\n- `/api/*` - Spot trading endpoints\n- `/sapi/*` - Binance API endpoints\n- Spot Websocket Market Stream\n- Spot User Data Stream\n- Spot WebSocket API\n- Comprehensive test cases and examples\n- Customizable base URL, request timeout and HTTP proxy\n- Response metadata display\n\n## \ud83d\udce6 **Installation**\n\n### Using pip (recommended)\n\n```bash\npip install sidan-binance-py\n```\n\n### Using uv (fastest)\n\n```bash\nuv add sidan-binance-py\n```\n\n### From source\n\n```bash\ngit clone https://github.com/sidan-lab/sidan-binance-py.git\ncd sidan-binance-py\nuv sync\n```\n\n## \ud83d\udcda **Documentation**\n\n- **API Documentation**: [https://sidan-lab.github.io/sidan-binance-py/](https://sidan-lab.github.io/sidan-binance-py/)\n- **Original Binance Connector**: [binance-connector.readthedocs.io](https://binance-connector.readthedocs.io)\n\n## \ud83d\udd04 **Key Differences from Original Connector**\n\n| Feature | Original Connector | This Fork (sidan-binance-py) |\n| ------------------ | ------------------------------- | --------------------------------- |\n| **Package Name** | `binance-connector` | `sidan-binance-py` |\n| **Import** | `from binance.spot import Spot` | `from binance.spot import Spot` \u2713 |\n| **Packaging** | setup.py | pyproject.toml + uv |\n| **Linting** | flake8 + black | ruff (faster, more features) |\n| **Pre-commit** | Basic setup | Comprehensive hooks |\n| **Documentation** | ReadTheDocs | GitHub Actions + Pages |\n| **Type Checking** | None | mypy configured |\n| **Python Support** | 3.8+ | 3.8+ (same) |\n\n> **\ud83d\udca1 Import Compatibility**: The import statements remain the same as the original connector, so you can easily switch between packages without changing your code!\n\n## \ud83d\ude80 **Quick Start**\n\n### RESTful APIs\n\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='<api_key>', api_secret='<api_secret>')\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```\n\nPlease find `examples` folder to check for more endpoints.\n\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 = \"<password_if_applicable>\"\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```\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\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`.<br/>\nIt's recommended to pass in the `base_url` parameter, even in production as Binance provides alternative URLs\nin case of performance issues:\n\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.<br/>\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.<br/>\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_.<br/>\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\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### 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```\n\nreturns:\n\n```python\n{'data': {'serverTime': 1587990847650}, 'limit_usage': {'x-mbx-used-weight': '31', 'x-mbx-used-weight-1m': '31'}}\n```\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\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\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\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```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\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## \ud83e\uddea **Development & Testing**\n\n### Running Tests\n\n```bash\n# Using the modern uv workflow\nmake test # Run all tests\nmake test-smoke # Run smoke tests only\n\n# Or manually with uv\nuv run pytest tests/ -q\n```\n\n### Code Quality\n\n```bash\nmake fmt # Format code with ruff\nmake lint # Lint code with ruff\nmake precommit # Run all pre-commit hooks\nmake type # Type check with mypy\n```\n\n### Documentation\n\n```bash\nmake docs-build # Build documentation\nmake docs-serve # Build and view documentation\n```\n\n### Development Setup\n\n```bash\ngit clone YOUR_REPO_URL\ncd sidan-binance-py\nmake install # Install dependencies\nmake hooks # Setup pre-commit hooks\n```\n\n## Limitation\n\nFutures and Vanilla Options APIs are not supported:\n\n- `/fapi/*`\n- `/dapi/*`\n- `/vapi/*`\n- Associated Websocket Market and User Data Streams\n\n## Contributing\n\nContributions are welcome.<br/>\nIf you've found a bug within this project, please open an issue to discuss what you would like to change.<br/>\nIf it's an issue with the API, please open a topic at [Binance Developer Community](https://dev.binance.vision)\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Modern, lightweight Python SDK for Binance public API - Fork of binance-connector with enhanced tooling and packaging",
"version": "0.0.2",
"project_urls": {
"Bug Tracker": "https://github.com/sidan-lab/sidan-binance-py/issues",
"Documentation": "https://sidan-lab.github.io/sidan-binance-py/",
"Homepage": "https://github.com/sidan-lab/sidan-binance-py",
"Original Connector": "https://github.com/binance/binance-connector-python",
"Repository": "https://github.com/sidan-lab/sidan-binance-py"
},
"split_keywords": [
"binance",
" cryptocurrency",
" public api",
" sdk",
" trading",
" websocket"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "328db4aa6fa77ddc8caa3f69761c986cebb76df9ee9ed81259d0a4082ed47ae5",
"md5": "53e1457cf3340c25874041480fe3174b",
"sha256": "623ad1fd389fd868fe81f66344eaa51f06fa13197e27f99e009754f39e0721d7"
},
"downloads": -1,
"filename": "sidan_binance_py-0.0.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "53e1457cf3340c25874041480fe3174b",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 86446,
"upload_time": "2025-09-02T00:25:02",
"upload_time_iso_8601": "2025-09-02T00:25:02.305209Z",
"url": "https://files.pythonhosted.org/packages/32/8d/b4aa6fa77ddc8caa3f69761c986cebb76df9ee9ed81259d0a4082ed47ae5/sidan_binance_py-0.0.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "17ea04d30a99efd87a92c28bfec35894263564fccdee0fb7941fcccc0265b407",
"md5": "57f4bebbac87f27ffb5c7a4c51e2ef0b",
"sha256": "79976760a4ce9f658c2dbb2a8e368e3c675b18d1345c6e49bcff98ec2eae3d00"
},
"downloads": -1,
"filename": "sidan_binance_py-0.0.2.tar.gz",
"has_sig": false,
"md5_digest": "57f4bebbac87f27ffb5c7a4c51e2ef0b",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 207108,
"upload_time": "2025-09-02T00:25:03",
"upload_time_iso_8601": "2025-09-02T00:25:03.305621Z",
"url": "https://files.pythonhosted.org/packages/17/ea/04d30a99efd87a92c28bfec35894263564fccdee0fb7941fcccc0265b407/sidan_binance_py-0.0.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-09-02 00:25:03",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "sidan-lab",
"github_project": "sidan-binance-py",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "sidan-binance-py"
}