# AioPyBit - Python Client for ByBit API (v5)
[](https://www.python.org/downloads/)
[](https://bybit-exchange.github.io/docs/v5/)
[](LICENSE)
AioPyBit is a modern and convenient Python client for the [ByBit](https://www.bybit.com/invite?ref=D0B6GN) cryptocurrency exchange API (v5). The module provides real-time access to market data and private account information via efficient WebSocket connections, and also supports HTTP requests with advanced error handling and auto-retry mechanisms.
## ๐ Features
- **๐ Advanced WebSocket Manager**: Unified manager for multiple connections and subscriptions
- **๐ Real-time Market Data**: Access live ticker, orderbook, trades, and kline data
- **๐ค Private Account Streams**: Monitor orders, executions, positions, and wallet balances
- **๐ Multiple Environments**: Support for mainnet, testnet, and demo environments
- **๐ช Robust Connection Management**: Automatic ping/pong, error handling, and reconnection
- **๐ Enhanced Retry Mechanism**: HTTP requests with exponential backoff retry
- **โก Auto-Reconnection**: WebSocket automatic reconnection with subscription restoration
- **๐ Subscription Management**: Easy subscribe/unsubscribe with pattern matching
- **๐ก๏ธ Type-Safe**: Full type annotations with protocol definitions
- **๐ฏ Easy Integration**: Simple async/await interface with callback handlers
- **๐งน Connection Cleanup**: Graceful cleanup and resource management
## ๐ Requirements
- Python 3.10+
- `websockets` >= 10.0
- `aiohttp` >= 3.8.0
- `asyncio` (built-in)
## ๐ ๏ธ Installation
```bash
pip install aiopybit
# The module is ready to use - no separate installation needed
```
## ๐๏ธ Architecture
### Core Components
- **`ByBitWebSocketManager`**: High-level manager for multiple WebSocket connections
- **`ByBitWebSocketClient`**: Low-level WebSocket client with connection management
- **`ByBitPublicStreamsMixin`**: Methods for public market data streams
- **`ByBitPrivateStreamsMixin`**: Methods for private account data streams
- **Protocol Definitions**: Type-safe interfaces in `protocols.py`
### Supported Streams
#### Public Streams (No Authentication Required)
- **Tickers**: Real-time price and volume data
- **Orderbook**: Live order book updates with configurable depth
- **Public Trades**: Recent trade executions
- **Klines/Candlesticks**: OHLCV data with various intervals
- **Liquidations**: Liquidation events
#### Private Streams (API Credentials Required)
- **Orders**: Real-time order status updates
- **Executions**: Trade execution notifications
- **Positions**: Position changes and P&L updates
- **Wallet**: Account balance updates
- **Greeks**: Option portfolio greeks (for options accounts)
## ๐ง Quick Start
### Simple WebSocket Manager Usage
```python
import asyncio
from aiopybit import ByBitClient
client = ByBitClient(API_KEY, API_SECRET, MODE)
async def handle_ticker(data):
ticker = data.get('data', {})
symbol = ticker.get('symbol', 'N/A')
price = ticker.get('lastPrice', 'N/A')
print(f'๐ {symbol}: ${price}')
async def main():
await client.ws.subscribe_to_ticker(
category='spot', symbol='BTCUSDT', on_message=handle_ticker
)
try:
while True:
await asyncio.sleep(1)
except KeyboardInterrupt:
pass
await client.close()
if __name__ == '__main__':
asyncio.run(main())
```
The `examples/` directory contains comprehensive usage examples:
## ๐ Authentication
For private streams, you need ByBit API credentials:
1. Create account at [ByBit](https://www.bybit.com/invite?ref=D0B6GN)
2. Go to [API Management](https://www.bybit.com/app/user/api-management)
3. Create new API key with appropriate permissions
4. Use testnet for development: [ByBit Testnet](https://testnet.bybit.com/)
### Required Permissions for Private Streams
- **Read**: For position, wallet, and order data
- **Trade**: For order and execution streams (if trading)
## ๐ Supported Environments
| Environment | Description | WebSocket URLs |
|-------------|-------------|----------------|
| `mainnet` | Production environment | `wss://stream.bybit.com/v5/` |
| `testnet` | Testing environment | `wss://stream-testnet.bybit.com/v5/` |
| `demo` | Demo environment (limited features) | `wss://stream-demo.bybit.com/v5/` |
## ๐ Market Categories
| Category | Description | Supported Streams |
|----------|-------------|-------------------|
| `linear` | USDT/USDC perpetual contracts | All public streams |
| `spot` | Spot trading pairs | Tickers, orderbook, trades |
| `option` | Options contracts | All public + greeks |
## ๐ Connection Management
The client includes robust connection management features:
- **Automatic Ping/Pong**: Maintains connection with 20-second intervals
- **Error Handling**: Graceful handling of connection errors
- **Resource Cleanup**: Proper cleanup of tasks and connections
## ๐ API Reference
### ByBitWebSocketManager
High-level WebSocket manager for multiple connections and subscriptions.
#### Constructor Parameters
- `mode`: Environment ('mainnet', 'testnet', 'demo')
- `api_key`: ByBit API key (required for private streams)
- `api_secret`: ByBit API secret (required for private streams)
- `ping_interval`: Ping interval in seconds (default: 20)
- `ping_timeout`: Ping timeout in seconds (default: 10)
- `auto_reconnect`: Enable auto-reconnection (default: True)
#### Connection Management Methods
- `get_websocket(channel_type)`: Get or create WebSocket for channel
- `close_all()`: Close all WebSocket connections
### Public Stream Methods
- `subscribe_to_ticker(category, symbol, on_message)`
- `subscribe_to_orderbook(category, symbol, on_message, depth)`
- `subscribe_to_public_trades(category, symbol, on_message)`
- `subscribe_to_kline(category, symbol, interval, on_message)`
- `subscribe_to_liquidations(category, symbol, on_message)`
### Private Stream Methods
- `subscribe_to_order(on_message)`
- `subscribe_to_execution(on_message)`
- `subscribe_to_position(on_message)`
- `subscribe_to_wallet(on_message)`
- `subscribe_to_greeks(on_message)`
### ByBitWebSocketClient
Low-level WebSocket client class with connection management.
#### Constructor Parameters
- `url`: WebSocket URL
- `api_key`: ByBit API key (optional for public streams)
- `api_secret`: ByBit API secret (optional for public streams)
- `ping_interval`: Ping interval in seconds (default: 20)
- `ping_timeout`: Ping timeout in seconds (default: 10)
- `auto_reconnect`: Enable auto-reconnection (default: True)
## ๐ Logging
Enable logging to monitor connection status and debug issues:
```python
import logging
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s'
)
# Set specific logger levels
logging.getLogger('aiopybit').setLevel(logging.INFO)
# For detailed debugging
logging.getLogger('aiopybit').setLevel(logging.DEBUG)
```
Log levels:
- `DEBUG`: Detailed connection and message information
- `INFO`: Connection status and important events
- `WARNING`: Connection issues and recoverable errors
- `ERROR`: Critical errors and failures
Example log output:
```
2024-01-15 10:30:45 [INFO] aiopybit: WebSocket connection for wss://stream.bybit.com/v5/public/linear established
2024-01-15 10:30:45 [INFO] aiopybit: โ
Subscribed to tickers.BTCUSDT
2024-01-15 10:30:46 [DEBUG] aiopybit: Sending ping for wss://stream.bybit.com/v5/public/linear
2024-01-15 10:31:05 [INFO] aiopybit: ๐ BTCUSDT: $45,123.45
```
## ๐ Related Links
- [ByBit Official Website](https://www.bybit.com/)
- [ByBit API Documentation](https://bybit-exchange.github.io/docs/v5/intro)
- [ByBit WebSocket Documentation](https://bybit-exchange.github.io/docs/v5/ws/connect)
- [ByBit Testnet](https://testnet.bybit.com/)
- [ByBit API Management](https://www.bybit.com/app/user/api-management)
- [ByBit Referal Program](https://www.bybit.com/invite?ref=D0B6GN)
## ๐ License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
## ๐ค Contributing
Contributions are welcome! Please feel free to submit pull requests or open issues for bugs and feature requests.
## โ ๏ธ Disclaimer
This software is for educational and development purposes. Use at your own risk. The authors are not responsible for any financial losses incurred through the use of this software.
---
**Happy Trading! ๐**
Raw data
{
"_id": null,
"home_page": null,
"name": "aiopybit",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.10",
"maintainer_email": null,
"keywords": "bybit, websocket, crypto, cryptocurrency, trading, exchange, async, aiohttp, python, api, websockets, market-data, orderbook, ticker, trades, bot",
"author": null,
"author_email": "Tsunami43 <n3m0_22@mail.ru>",
"download_url": "https://files.pythonhosted.org/packages/a2/79/c4205158e349a7b549ed02f85c49424cff07603e9c7aae01b6a2144790ac/aiopybit-0.1.2.tar.gz",
"platform": null,
"description": "# AioPyBit - Python Client for ByBit API (v5)\n\n[](https://www.python.org/downloads/)\n[](https://bybit-exchange.github.io/docs/v5/)\n[](LICENSE)\n\nAioPyBit is a modern and convenient Python client for the [ByBit](https://www.bybit.com/invite?ref=D0B6GN) cryptocurrency exchange API (v5). The module provides real-time access to market data and private account information via efficient WebSocket connections, and also supports HTTP requests with advanced error handling and auto-retry mechanisms.\n\n## \ud83d\ude80 Features\n\n- **\ud83d\udd17 Advanced WebSocket Manager**: Unified manager for multiple connections and subscriptions\n- **\ud83d\udcca Real-time Market Data**: Access live ticker, orderbook, trades, and kline data\n- **\ud83d\udc64 Private Account Streams**: Monitor orders, executions, positions, and wallet balances\n- **\ud83c\udf0d Multiple Environments**: Support for mainnet, testnet, and demo environments\n- **\ud83d\udcaa Robust Connection Management**: Automatic ping/pong, error handling, and reconnection\n- **\ud83d\udd04 Enhanced Retry Mechanism**: HTTP requests with exponential backoff retry\n- **\u26a1 Auto-Reconnection**: WebSocket automatic reconnection with subscription restoration\n- **\ud83d\udcdd Subscription Management**: Easy subscribe/unsubscribe with pattern matching\n- **\ud83d\udee1\ufe0f Type-Safe**: Full type annotations with protocol definitions\n- **\ud83c\udfaf Easy Integration**: Simple async/await interface with callback handlers\n- **\ud83e\uddf9 Connection Cleanup**: Graceful cleanup and resource management\n\n## \ud83d\udccb Requirements\n\n- Python 3.10+\n- `websockets` >= 10.0\n- `aiohttp` >= 3.8.0\n- `asyncio` (built-in)\n\n## \ud83d\udee0\ufe0f Installation\n\n```bash\npip install aiopybit\n\n# The module is ready to use - no separate installation needed\n```\n\n## \ud83c\udfd7\ufe0f Architecture\n\n### Core Components\n\n- **`ByBitWebSocketManager`**: High-level manager for multiple WebSocket connections\n- **`ByBitWebSocketClient`**: Low-level WebSocket client with connection management\n- **`ByBitPublicStreamsMixin`**: Methods for public market data streams\n- **`ByBitPrivateStreamsMixin`**: Methods for private account data streams\n- **Protocol Definitions**: Type-safe interfaces in `protocols.py`\n\n### Supported Streams\n\n#### Public Streams (No Authentication Required)\n- **Tickers**: Real-time price and volume data\n- **Orderbook**: Live order book updates with configurable depth\n- **Public Trades**: Recent trade executions\n- **Klines/Candlesticks**: OHLCV data with various intervals\n- **Liquidations**: Liquidation events\n\n#### Private Streams (API Credentials Required)\n- **Orders**: Real-time order status updates\n- **Executions**: Trade execution notifications\n- **Positions**: Position changes and P&L updates\n- **Wallet**: Account balance updates\n- **Greeks**: Option portfolio greeks (for options accounts)\n\n## \ud83d\udd27 Quick Start\n\n### Simple WebSocket Manager Usage\n\n```python\nimport asyncio\nfrom aiopybit import ByBitClient\n\n\nclient = ByBitClient(API_KEY, API_SECRET, MODE)\n\n\nasync def handle_ticker(data):\n\tticker = data.get('data', {})\n\tsymbol = ticker.get('symbol', 'N/A')\n\tprice = ticker.get('lastPrice', 'N/A')\n\tprint(f'\ud83d\udcca {symbol}: ${price}')\n\n\nasync def main():\n\tawait client.ws.subscribe_to_ticker(\n\t\tcategory='spot', symbol='BTCUSDT', on_message=handle_ticker\n\t)\n\ttry:\n\t\twhile True:\n\t\t\tawait asyncio.sleep(1)\n\texcept KeyboardInterrupt:\n\t\tpass\n\n\tawait client.close()\n\n\nif __name__ == '__main__':\n\tasyncio.run(main())\n```\n\nThe `examples/` directory contains comprehensive usage examples:\n\n\n## \ud83d\udd10 Authentication\n\nFor private streams, you need ByBit API credentials:\n\n1. Create account at [ByBit](https://www.bybit.com/invite?ref=D0B6GN)\n2. Go to [API Management](https://www.bybit.com/app/user/api-management)\n3. Create new API key with appropriate permissions\n4. Use testnet for development: [ByBit Testnet](https://testnet.bybit.com/)\n\n### Required Permissions for Private Streams\n- **Read**: For position, wallet, and order data\n- **Trade**: For order and execution streams (if trading)\n\n## \ud83c\udf10 Supported Environments\n\n| Environment | Description | WebSocket URLs |\n|-------------|-------------|----------------|\n| `mainnet` | Production environment | `wss://stream.bybit.com/v5/` |\n| `testnet` | Testing environment | `wss://stream-testnet.bybit.com/v5/` |\n| `demo` | Demo environment (limited features) | `wss://stream-demo.bybit.com/v5/` |\n\n## \ud83d\udcca Market Categories\n\n| Category | Description | Supported Streams |\n|----------|-------------|-------------------|\n| `linear` | USDT/USDC perpetual contracts | All public streams |\n| `spot` | Spot trading pairs | Tickers, orderbook, trades |\n| `option` | Options contracts | All public + greeks |\n\n## \ud83d\udd04 Connection Management\n\nThe client includes robust connection management features:\n\n- **Automatic Ping/Pong**: Maintains connection with 20-second intervals\n- **Error Handling**: Graceful handling of connection errors\n- **Resource Cleanup**: Proper cleanup of tasks and connections\n\n## \ud83d\udcd6 API Reference\n\n### ByBitWebSocketManager\n\nHigh-level WebSocket manager for multiple connections and subscriptions.\n\n#### Constructor Parameters\n- `mode`: Environment ('mainnet', 'testnet', 'demo')\n- `api_key`: ByBit API key (required for private streams)\n- `api_secret`: ByBit API secret (required for private streams)\n- `ping_interval`: Ping interval in seconds (default: 20)\n- `ping_timeout`: Ping timeout in seconds (default: 10)\n- `auto_reconnect`: Enable auto-reconnection (default: True)\n\n#### Connection Management Methods\n- `get_websocket(channel_type)`: Get or create WebSocket for channel\n- `close_all()`: Close all WebSocket connections\n\n### Public Stream Methods\n- `subscribe_to_ticker(category, symbol, on_message)`\n- `subscribe_to_orderbook(category, symbol, on_message, depth)`\n- `subscribe_to_public_trades(category, symbol, on_message)`\n- `subscribe_to_kline(category, symbol, interval, on_message)`\n- `subscribe_to_liquidations(category, symbol, on_message)`\n\n### Private Stream Methods\n- `subscribe_to_order(on_message)`\n- `subscribe_to_execution(on_message)`\n- `subscribe_to_position(on_message)`\n- `subscribe_to_wallet(on_message)`\n- `subscribe_to_greeks(on_message)`\n\n### ByBitWebSocketClient\n\nLow-level WebSocket client class with connection management.\n\n#### Constructor Parameters\n- `url`: WebSocket URL\n- `api_key`: ByBit API key (optional for public streams)\n- `api_secret`: ByBit API secret (optional for public streams)\n- `ping_interval`: Ping interval in seconds (default: 20)\n- `ping_timeout`: Ping timeout in seconds (default: 10)\n- `auto_reconnect`: Enable auto-reconnection (default: True)\n\n## \ud83d\udcdd Logging\n\nEnable logging to monitor connection status and debug issues:\n\n```python\nimport logging\n\n# Configure logging\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s [%(levelname)s] %(name)s: %(message)s'\n)\n\n# Set specific logger levels\nlogging.getLogger('aiopybit').setLevel(logging.INFO)\n\n# For detailed debugging\nlogging.getLogger('aiopybit').setLevel(logging.DEBUG)\n```\n\nLog levels:\n- `DEBUG`: Detailed connection and message information\n- `INFO`: Connection status and important events \n- `WARNING`: Connection issues and recoverable errors\n- `ERROR`: Critical errors and failures\n\nExample log output:\n```\n2024-01-15 10:30:45 [INFO] aiopybit: WebSocket connection for wss://stream.bybit.com/v5/public/linear established\n2024-01-15 10:30:45 [INFO] aiopybit: \u2705 Subscribed to tickers.BTCUSDT\n2024-01-15 10:30:46 [DEBUG] aiopybit: Sending ping for wss://stream.bybit.com/v5/public/linear\n2024-01-15 10:31:05 [INFO] aiopybit: \ud83d\udcca BTCUSDT: $45,123.45\n```\n\n## \ud83d\udd17 Related Links\n\n- [ByBit Official Website](https://www.bybit.com/)\n- [ByBit API Documentation](https://bybit-exchange.github.io/docs/v5/intro)\n- [ByBit WebSocket Documentation](https://bybit-exchange.github.io/docs/v5/ws/connect)\n- [ByBit Testnet](https://testnet.bybit.com/)\n- [ByBit API Management](https://www.bybit.com/app/user/api-management)\n- [ByBit Referal Program](https://www.bybit.com/invite?ref=D0B6GN)\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.\n\n## \ud83e\udd1d Contributing\n\nContributions are welcome! Please feel free to submit pull requests or open issues for bugs and feature requests.\n\n## \u26a0\ufe0f Disclaimer\n\nThis software is for educational and development purposes. Use at your own risk. The authors are not responsible for any financial losses incurred through the use of this software.\n\n---\n\n**Happy Trading! \ud83d\ude80**\n",
"bugtrack_url": null,
"license": null,
"summary": "Asynchronous Python client for the ByBit API",
"version": "0.1.2",
"project_urls": {
"Homepage": "https://github.com/Tsunami43/aiopybit",
"Repository": "https://github.com/Tsunami43/aiopybit.git"
},
"split_keywords": [
"bybit",
" websocket",
" crypto",
" cryptocurrency",
" trading",
" exchange",
" async",
" aiohttp",
" python",
" api",
" websockets",
" market-data",
" orderbook",
" ticker",
" trades",
" bot"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "b6a72255a48fc18a502be5b17d792e168f862c802da0252bc3cc5c8f70a6da02",
"md5": "a3cc5c9d60334913474c3be7bdb9990e",
"sha256": "cb4227d7265a5ac90e692e57161bca5c2d1847ac3c0048197e74b14c5732608f"
},
"downloads": -1,
"filename": "aiopybit-0.1.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "a3cc5c9d60334913474c3be7bdb9990e",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.10",
"size": 22839,
"upload_time": "2025-08-23T06:14:02",
"upload_time_iso_8601": "2025-08-23T06:14:02.240806Z",
"url": "https://files.pythonhosted.org/packages/b6/a7/2255a48fc18a502be5b17d792e168f862c802da0252bc3cc5c8f70a6da02/aiopybit-0.1.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "a279c4205158e349a7b549ed02f85c49424cff07603e9c7aae01b6a2144790ac",
"md5": "ad8a26d52b08335b1453d7e0476d6913",
"sha256": "5eaf50d4f25f49a3a45c03e89fb60344eb18e406faf4b8811c5b35e52693e763"
},
"downloads": -1,
"filename": "aiopybit-0.1.2.tar.gz",
"has_sig": false,
"md5_digest": "ad8a26d52b08335b1453d7e0476d6913",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.10",
"size": 21587,
"upload_time": "2025-08-23T06:14:03",
"upload_time_iso_8601": "2025-08-23T06:14:03.536149Z",
"url": "https://files.pythonhosted.org/packages/a2/79/c4205158e349a7b549ed02f85c49424cff07603e9c7aae01b6a2144790ac/aiopybit-0.1.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-23 06:14:03",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "Tsunami43",
"github_project": "aiopybit",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "aiopybit"
}