这是Binance交易所REST API v3的非官方Python封装器,我与Binance没有任何关系,使用时风险自负。
如果你来这里寻找购买加密货币的Binance交易所,那么请到这里。如果您想与Binance进行自动交互,请继续关注。
如果你对Binance的新DEX Binance Chain感兴趣,请看我的python-binance-chain库。
Binance的异步基础知识
了解Binance订单过滤器
请确保你经常更新,并查看Changelog以了解新功能和错误修复。
秒合约交易所开发详细丨秒合约交易所系统开发详细及规则丨秒合约交易所系统源码部署
数字货币交易所开发源码丨数字货币交易所系统开发(详细及逻辑)
交易所开发正式版丨区块链交易所系统开发实现技术功能及源码
交易所开发案例丨交易所系统开发(详细及流程)丨交易所成熟及源码系统
交易所开发(稳定版)丨交易所系统开发(方案及逻辑)丨 交易所系统源码功能
什么是去中心化交易所系统开发丨浅谈uniswap丨justswap
交易所源码(整体架构演示)
交易所搭建,交易所源码是怎么开发的?
区块链交易所怎么搭建?
区块链交易所平台中常见的开发模式有哪些?
区块链交易所如何开发(介绍区块链应用开发的流程)
区块链交易所开发的玩法介绍
特点
实施所有常规、市场数据和账户端点。
实施Asyncio
支持现货、期货和普通期权的Testnet。
简单处理认证
不需要自己生成时间戳,包装器为你做这件事
响应异常处理
Websocket处理与重新连接和复用连接
符号深度缓存
历史上的Kline/Candle取数功能
提款功能
存款地址
保证金交易
期货交易
香草期权
支持其他域名(.us、.jp等)。
升级到V1.0.0+版本
突破性变化包括从wapi迁移到sapi端点,这与Binance文档中详述的钱包端点有关。
另一个突破性变化是websocket流和深度缓存管理器,它们已被转换为使用异步上下文管理器。见下面异步部分的例子,或查看websockets和深度缓存文档。
快速入门
在Binance注册一个账户。
生成一个API密钥并分配相关权限。
如果您使用的是美国、日本或其他顶级域名的交易所,那么在创建客户端时请确保传递tld='us'。
要使用现货或香草期权测试网,请在创建客户端时传递testnet=True。
pip install python-binance
from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager
client = Client(api_key, api_secret)
get market depth
depth = client.get_order_book(symbol='BNBBTC')
place a test market buy order, to place an actual order use the create_order function
order = client.create_test_order(
symbol='BNBBTC',
side=Client.SIDE_BUY,
type=Client.ORDER_TYPE_MARKET,
quantity=100)
get all symbol prices
prices = client.get_all_tickers()
withdraw 100 ETH
check docs for assumptions around withdrawals
from binance.exceptions import BinanceAPIException
try:
result = client.withdraw(
asset='ETH',
address='<eth_address>',
amount=100)
except BinanceAPIException as e:
print(e)
else:
print("Success")
fetch list of withdrawals
withdraws = client.get_withdraw_history()
fetch list of ETH withdrawals
eth_withdraws = client.get_withdraw_history(coin='ETH')
get a deposit address for BTC
address = client.get_deposit_address(coin='BTC')
get historical kline data from any date range
fetch 1 minute klines for the last day up until now
klines = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC")
fetch 30 minute klines for the last month of 2017
klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1 Dec, 2017", "1 Jan, 2018")
fetch weekly klines since it listed
klines = client.get_historical_klines("NEOBTC", Client.KLINE_INTERVAL_1WEEK, "1 Jan, 2017")
socket manager using threads
twm = ThreadedWebsocketManager()
twm.start()
depth cache manager using threads
dcm = ThreadedDepthCacheManager()
dcm.start()
def handle_socket_message(msg):
print(f"message type: {msg['e']}")
print(msg)
def handle_dcm_message(depth_cache):
print(f"symbol {depth_cache.symbol}")
print("top 5 bids")
print(depth_cache.get_bids()[:5])
print("top 5 asks")
print(depth_cache.get_asks()[:5])
print("last update time {}".format(depth_cache.update_time))
twm.start_kline_socket(callback=handle_socket_message, symbol='BNBBTC')
dcm.start_depth_cache(callback=handle_dcm_message, symbol='ETHBTC')
replace with a current options symbol
options_symbol = 'BTC-210430-36000-C'
dcm.start_options_depth_cache(callback=handle_dcm_message, symbol=options_symbol)
join the threaded managers to the main thread
twm.join()
dcm.join()
For more check out the documentation.
Async Example
Read Async basics for Binance for more information.
import asyncio
import json
from binance import AsyncClient, DepthCacheManager, BinanceSocketManager
async def main():
# initialise the client
client = await AsyncClient.create()
# run some simple requests
print(json.dumps(await client.get_exchange_info(), indent=2))
print(json.dumps(await client.get_symbol_ticker(symbol="BTCUSDT"), indent=2))
# initialise websocket factory manager
bsm = BinanceSocketManager(client)
# create listener using async with
# this will exit and close the connection after 5 messages
async with bsm.trade_socket('ETHBTC') as ts:
for _ in range(5):
res = await ts.recv()
print(f'recv {res}')
# get historical kline data from any date range
# fetch 1 minute klines for the last day up until now
klines = client.get_historical_klines("BNBBTC", AsyncClient.KLINE_INTERVAL_1MINUTE, "1 day ago UTC")
# use generator to fetch 1 minute klines for the last day up until now
async for kline in await client.get_historical_klines_generator("BNBBTC", AsyncClient.KLINE_INTERVAL_1MINUTE, "1 day ago UTC"):
print(kline)
# fetch 30 minute klines for the last month of 2017
klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1 Dec, 2017", "1 Jan, 2018")
# fetch weekly klines since it listed
klines = client.get_historical_klines("NEOBTC", Client.KLINE_INTERVAL_1WEEK, "1 Jan, 2017")
# setup an async context the Depth Cache and exit after 5 messages
async with DepthCacheManager(client, symbol='ETHBTC') as dcm_socket:
for _ in range(5):
depth_cache = await dcm_socket.recv()
print(f"symbol {depth_cache.symbol} updated:{depth_cache.update_time}")
print("Top 5 asks:")
print(depth_cache.get_asks()[:5])
print("Top 5 bids:")
print(depth_cache.get_bids()[:5])
# Vanilla options Depth Cache works the same, update the symbol to a current one
options_symbol = 'BTC-210430-36000-C'
async with OptionsDepthCacheManager(client, symbol=options_symbol) as dcm_socket:
for _ in range(5):
depth_cache = await dcm_socket.recv()
count += 1
print(f"symbol {depth_cache.symbol} updated:{depth_cache.update_time}")
print("Top 5 asks:")
print(depth_cache.get_asks()[:5])
print("Top 5 bids:")
print(depth_cache.get_bids()[:5])
await client.close_connection()
if name == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
捐赠
如果这个图书馆帮助了你,请随时捐赠。
ETH: 0xD7a7fDdCfA687073d7cC93E9E51829a727f9fE70
LTC: LPC5vw9ajR1YndE1hYVeo3kJ9LdHjcRCUZ
NEO。AVJB4ZgN7VgSUtArCt94y7ZYT6d5NDfpBo
BTC: 1Dknp6L6oRZrHDECRedihPzx2sSfmvEBys
其他交易所
如果你使用Binance Chain,请查看我的python-binance-chain库。
如果你使用Kucoin,请查看我的python-kucoin库。
如果你使用IDEX,请查看我的python-idex库。