Binance异步Python客户端
项目描述
binance-aio 0.0.3
公告:binance-aio
已被新的库 cryptoxlib-aio
替换。 cryptoxlib-aio
提供与 binance-aio
相同的功能,同时还提供对多个加密交易所和其他(主要是技术性)新功能的访问。您仍然可以使用 binance-aio
,但请注意,将不会实现新的功能/错误修复。我们建议迁移到 cryptoxlib-aio
。
binance-aio
是一个提供对 binance加密交易所 访问的Python库。库实现了binance的REST API以及websockets。
binance-aio
是一个利用Python和异步库(主要是 异步websockets 和 aiohttp)的现代功能的异步库。
有关更改,请参阅 更改日志。
功能
- 访问有限的binance REST API(账户详情、市场数据、订单管理等)和websockets(账户推送、市场数据推送、订单簿推送等)。缺失的REST调用和websocket流将在请求和我们的可用性基础上添加。
- 将通道捆绑在一个或多个websockets中并行处理
- 精益架构为未来的扩展和定制奠定基础
- 完全异步设计,旨在实现最佳性能
安装
pip install binance-aio
先决条件
由于库中使用的依赖关系和Python特性,请确保您使用Python 3.6
或 3.7
。
在开始使用 binance-aio
之前,您需要做的是
- 从您的Binance账户下载您的Binance API和SECRET密钥
- 生成将用于保护SSL连接的证书。可以使用以下方法轻松生成
certificate.pem
证书
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out certificate.pem
示例
REST API
import asyncio
import pathlib
import logging
import os
from datetime import datetime
from binance.BinanceClient import BinanceClient
from binance.Pair import Pair
from binance.enums import OrderSide, TimeInForce, OrderResponseType
LOG = logging.getLogger("binance")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def account_update(response : dict) -> None:
print(f"Callback {account_update.__name__}: [{response}]")
async def order_book_update(response : dict) -> None:
print(f"Callback {order_book_update.__name__}: [{response}]")
async def trade_update(response : dict) -> None:
local_timestamp_ms = int(datetime.now().timestamp() * 1000)
server_timestamp_ms = response['E']
print(f"Trade update timestamp diff [ms]: {local_timestamp_ms - server_timestamp_ms}")
async def orderbook_ticker_update(response : dict) -> None:
print(f"Callback {orderbook_ticker_update.__name__}: [{response}]")
async def run():
print("STARTING BINANCE CLIENT\n")
# to generate a certificate use 'openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out certificate.pem'
certificate_path = pathlib.Path(__file__).with_name("certificate.pem")
# to retrieve your API/SEC key go to your binance website, create the keys and store them in APIKEY/SECKEY
# environment variables
api_key = os.environ['APIKEY']
sec_key = os.environ['SECKEY']
client = BinanceClient(certificate_path, api_key, sec_key)
# REST api calls
print("REST API")
print("\nPing:")
await client.ping()
print("\nServer time:")
await client.get_time()
print("\nExchange info:")
await client.get_exchange_info()
print("\nBest order book ticker:")
await client.get_best_orderbook_ticker(pair = Pair('ETH', 'BTC'))
print("\nAccount:")
await client.get_account(recv_window_ms = 5000)
print("\nCreate limit order:")
await client.create_limit_order(Pair("ETH", "BTC"), OrderSide.BUY, "1", "0", time_in_force = TimeInForce.GOOD_TILL_CANCELLED,
new_order_response_type = OrderResponseType.FULL)
print("\nDelete order:")
await client.delete_order(pair = Pair('ETH', 'BTC'), order_id = "1")
await client.close()
if __name__ == "__main__":
asyncio.run(run())
WEBSOCKETS
import asyncio
import pathlib
import logging
import os
from datetime import datetime
from binance.BinanceClient import BinanceClient
from binance.Pair import Pair
from binance.subscriptions import BestOrderBookTickerSubscription, TradeSubscription, AccountSubscription
LOG = logging.getLogger("binance")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def account_update(response : dict) -> None:
print(f"Callback {account_update.__name__}: [{response}]")
async def order_book_update(response : dict) -> None:
print(f"Callback {order_book_update.__name__}: [{response}]")
async def trade_update(response : dict) -> None:
local_timestamp_ms = int(datetime.now().timestamp() * 1000)
server_timestamp_ms = response['E']
print(f"Trade update timestamp diff [ms]: {local_timestamp_ms - server_timestamp_ms}")
async def orderbook_ticker_update(response : dict) -> None:
print(f"Callback {orderbook_ticker_update.__name__}: [{response}]")
async def run():
print("STARTING BINANCE CLIENT\n")
# to generate a certificate use 'openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out certificate.pem'
certificate_path = pathlib.Path(__file__).with_name("certificate.pem")
# to retrieve your API/SEC key go to your binance website, create the keys and store them in API_KEY/SEC_KEY
# environment variables
api_key = os.environ['APIKEY']
sec_key = os.environ['SECKEY']
client = BinanceClient(certificate_path, api_key, sec_key)
# Websockets
print("\nWEBSOCKETS\n")
print("\nCreate listen key:")
listen_key = await client.get_listen_key()
# Bundle several subscriptions into a single websocket
client.compose_subscriptions([
BestOrderBookTickerSubscription(callbacks = [orderbook_ticker_update]),
TradeSubscription(pair = Pair('ETH', 'BTC'), callbacks = [trade_update])
])
# Bundle another subscriptions into a separate websocket
print(listen_key)
client.compose_subscriptions([
AccountSubscription(client, callbacks = [account_update])
])
# Execute all websockets asynchronously
await client.start_subscriptions()
await client.close()
if __name__ == "__main__":
asyncio.run(run())
所有示例都可以在GitHub仓库中的 client-example/client.py
文件中找到。
支持
如果您喜欢这个库,并且想要支持其进一步的开发、增强和错误修复,那么如果您
- 提交错误报告、建议、拉取请求...
- 传播信息
- 捐赠任意金额的小费
- BTC: 15JUgVq3YFoPedEj5wgQgvkZRx5HQoKJC4
- ETH: 0xf29304b6af5831030ba99aceb290a3a2129b993d
- ADA: DdzFFzCqrhshyLV3wktXFvConETEr9mCfrMo9V3dYz4pz6yNq9PjJusfnn4kzWKQR91pWecEbKoHodPaJzgBHdV2AKeDSfR4sckrEk79
- XRP: rhVWrjB9EGDeK4zuJ1x2KXSjjSpsDQSaU6 + 标签 599790141
联系
如果您想取得联系,请
- 最好使用Github Issues,或者
- 发送电子邮件到
隶属关系
如果您对自动交易机器人感兴趣,请查看我们的其他项目 creten。
项目详情
下载文件
下载适用于您平台文件。如果您不确定选择哪个,请了解有关 安装软件包 的更多信息。
源分发
binance-aio-0.0.3.tar.gz (12.0 kB 查看哈希值)
构建分发
binance_aio-0.0.3-py3-none-any.whl (11.2 kB 查看哈希值)