Socket
Book a DemoInstallSign in
Socket

aiopybit

Package Overview
Dependencies
Maintainers
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

aiopybit

Asynchronous Python client for the ByBit API

0.1.2
pipPyPI
Maintainers
1

AioPyBit - Python Client for ByBit API (v5)

Python Version ByBit API License

AioPyBit is a modern and convenient Python client for the ByBit 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

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

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:

Required Permissions for Private Streams

  • Read: For position, wallet, and order data
  • Trade: For order and execution streams (if trading)

๐ŸŒ Supported Environments

EnvironmentDescriptionWebSocket URLs
mainnetProduction environmentwss://stream.bybit.com/v5/
testnetTesting environmentwss://stream-testnet.bybit.com/v5/
demoDemo environment (limited features)wss://stream-demo.bybit.com/v5/

๐Ÿ“Š Market Categories

CategoryDescriptionSupported Streams
linearUSDT/USDC perpetual contractsAll public streams
spotSpot trading pairsTickers, orderbook, trades
optionOptions contractsAll 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:

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

๐Ÿ“„ License

This project is licensed under the MIT License. See the 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! ๐Ÿš€

Keywords

bybit

FAQs

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with โšก๏ธ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.