Skip to main content

币安 REST API python 实现

项目描述

2021 年 9 月 27 日更新

https://img.shields.io/pypi/v/python-binance.svg https://img.shields.io/pypi/l/python-binance.svg https://img.shields.io/travis/sammchardy/python-binance.svg https://img.shields.io/coveralls/sammchardy/python-binance.svg https://img.shields.io/pypi/wheel/python-binance.svg https://img.shields.io/pypi/pyversions/python-binance.svg

这是Binance exchange REST API v3的非官方 Python 包装器。我绝不隶属于 Binance,使用风险自负。

如果你来这里是为了寻找币安交易所购买加密货币,那就去这里吧。如果你想自动化与 Binance 的交互,请坚持。

如果您对币安的新 DEX 币安链感兴趣,请查看我的python-binance-chain 库

源代码

https://github.com/sammchardy/python-binance

文档

https://python-binance.readthedocs.io/en/latest/

币安 API 电报

https://t.me/binance_api_english

包含异步示例的博客

https://sammchardy.github.io

确保您经常更新并检查更新日志以获取新功能和错误修复。

特征

  • 实施所有通用、市场数据和账户端点。

  • 异步实现

  • 对现货、期货和普通期权的测试网支持

  • 简单的身份验证处理

  • 无需自己生成时间戳,包装器为您完成

  • 响应异常处理

  • 使用重新连接和多路复用连接处理 Websocket

  • 符号深度缓存

  • 历史K线/蜡烛提取功能

  • 提现功能

  • 存款地址

  • 保证金交易

  • 期货交易

  • 香草选项

  • 支持其他域(.us、.jp 等)

升级到 v1.0.0+

重大更改包括从 wapi 到 sapi 端点的迁移,这与Binance Docs中详述的钱包端点相关

另一个重大变化是针对 websocket 流和深度缓存管理器,它们已被转换为使用异步上下文管理器。请参阅下面异步部分中的示例或查看 websockets深度缓存文档。

快速开始

在 Binance 注册一个帐户

生成 API Key并分配相关权限。

如果您使用来自美国、日本或其他 TLD 的交换,请确保在创建客户端时传递tld='us' 。

要使用SpotVanilla Options测试网,请在创建客户端时传递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()

有关更多信息,请查看文档

异步示例

阅读Binance 的异步基础知识以 获取更多信息。

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())

其他交易所

如果您使用Binance Chain,请查看我的python-binance-chain库。

如果你使用Kucoin,请查看我的python-kucoin库。

如果您使用IDEX,请查看我的python-idex库。

https://ga-beacon.appspot.com/UA-111417213-1/github/python-binance?pixel&useReferer

项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

binance-sync-1.0.16.tar.gz (64.7 kB 查看哈希)

已上传 source