![](/img/trans.png)
[英]ModuleNotFoundError: No module named 'binance.client'; 'binance' is not a package
[英]Why am I getting this error 'ModuleNotFoundError: No module named 'binance.client'; 'binance' is not a package' after binance installed?
我正在使用 Visual Studio 代码尝试从 Binance 中提取蜡烛,但我不断收到以下错误:
ModuleNotFoundError: No module named 'binance.client'; 'binance' is not a package
这是导致错误的代码行:
from binance.client import Client
我确保我 pip 将 python-binance 安装到 python 的正确版本,并且从我读到的内容中我猜测路径有问题,但我不确定要寻找什么。 我运行以下代码检查路径
import pprint, os
import binance
pprint.pprint(os.path.abspath(binance.__file__))
这是我的结果
'/Users/myName/.local/lib/python3.7/site-packages/binance.py'
我读到拥有名为 binance.py 的文件可能会弄乱它,但这是下载时给出的名称。 如果您对这里的外观感到好奇,那就是:
import hmac
import hashlib
import logging
import requests
import time
try:
from urllib import urlencode
# for python3
except ImportError:
from urllib.parse import urlencode
ENDPOINT = "https://www.binance.com"
BUY = "BUY"
SELL = "SELL"
LIMIT = "LIMIT"
MARKET = "MARKET"
GTC = "GTC"
IOC = "IOC"
options = {}
def set(apiKey, secret):
"""Set API key and secret.
Must be called before any making any signed API calls.
"""
options["apiKey"] = apiKey
options["secret"] = secret
def prices():
"""Get latest prices for all symbols."""
data = request("GET", "/api/v1/ticker/allPrices")
return {d["symbol"]: d["price"] for d in data}
def tickers():
"""Get best price/qty on the order book for all symbols."""
data = request("GET", "/api/v1/ticker/allBookTickers")
return {d["symbol"]: {
"bid": d["bidPrice"],
"ask": d["askPrice"],
"bidQty": d["bidQty"],
"askQty": d["askQty"],
} for d in data}
def depth(symbol, **kwargs):
"""Get order book.
Args:
symbol (str)
limit (int, optional): Default 100. Must be one of 50, 20, 100, 500, 5,
200, 10.
"""
params = {"symbol": symbol}
params.update(kwargs)
data = request("GET", "/api/v1/depth", params)
return {
"bids": {px: qty for px, qty, _ in data["bids"]},
"asks": {px: qty for px, qty, _ in data["asks"]},
}
def klines(symbol, interval, **kwargs):
"""Get kline/candlestick bars for a symbol.
Klines are uniquely identified by their open time. If startTime and endTime
are not sent, the most recent klines are returned.
Args:
symbol (str)
interval (str)
limit (int, optional): Default 500; max 500.
startTime (int, optional)
endTime (int, optional)
"""
params = {"symbol": symbol, "interval": interval}
params.update(kwargs)
data = request("GET", "/api/v1/klines", params)
return [{
"openTime": d[0],
"open": d[1],
"high": d[2],
"low": d[3],
"close": d[4],
"volume": d[5],
"closeTime": d[6],
"quoteVolume": d[7],
"numTrades": d[8],
} for d in data]
def balances():
"""Get current balances for all symbols."""
data = signedRequest("GET", "/api/v3/account", {})
if 'msg' in data:
raise ValueError("Error from exchange: {}".format(data['msg']))
return {d["asset"]: {
"free": d["free"],
"locked": d["locked"],
} for d in data.get("balances", [])}
def order(symbol, side, quantity, price, orderType=LIMIT, timeInForce=GTC,
test=False, **kwargs):
"""Send in a new order.
Args:
symbol (str)
side (str): BUY or SELL.
quantity (float, str or decimal)
price (float, str or decimal)
orderType (str, optional): LIMIT or MARKET.
timeInForce (str, optional): GTC or IOC.
test (bool, optional): Creates and validates a new order but does not
send it into the matching engine. Returns an empty dict if
successful.
newClientOrderId (str, optional): A unique id for the order.
Automatically generated if not sent.
stopPrice (float, str or decimal, optional): Used with stop orders.
icebergQty (float, str or decimal, optional): Used with iceberg orders.
"""
params = {
"symbol": symbol,
"side": side,
"type": orderType,
"timeInForce": timeInForce,
"quantity": formatNumber(quantity),
"price": formatNumber(price),
}
params.update(kwargs)
path = "/api/v3/order/test" if test else "/api/v3/order"
data = signedRequest("POST", path, params)
return data
def orderStatus(symbol, **kwargs):
"""Check an order's status.
Args:
symbol (str)
orderId (int, optional)
origClientOrderId (str, optional)
recvWindow (int, optional)
"""
params = {"symbol": symbol}
params.update(kwargs)
data = signedRequest("GET", "/api/v3/order", params)
return data
def cancel(symbol, **kwargs):
"""Cancel an active order.
Args:
symbol (str)
orderId (int, optional)
origClientOrderId (str, optional)
newClientOrderId (str, optional): Used to uniquely identify this
cancel. Automatically generated by default.
recvWindow (int, optional)
"""
params = {"symbol": symbol}
params.update(kwargs)
data = signedRequest("DELETE", "/api/v3/order", params)
return data
def openOrders(symbol, **kwargs):
"""Get all open orders on a symbol.
Args:
symbol (str)
recvWindow (int, optional)
"""
params = {"symbol": symbol}
params.update(kwargs)
data = signedRequest("GET", "/api/v3/openOrders", params)
return data
def allOrders(symbol, **kwargs):
"""Get all account orders; active, canceled, or filled.
If orderId is set, it will get orders >= that orderId. Otherwise most
recent orders are returned.
Args:
symbol (str)
orderId (int, optional)
limit (int, optional): Default 500; max 500.
recvWindow (int, optional)
"""
params = {"symbol": symbol}
params.update(kwargs)
data = signedRequest("GET", "/api/v3/allOrders", params)
return data
def myTrades(symbol, **kwargs):
"""Get trades for a specific account and symbol.
Args:
symbol (str)
limit (int, optional): Default 500; max 500.
fromId (int, optional): TradeId to fetch from. Default gets most recent
trades.
recvWindow (int, optional)
"""
params = {"symbol": symbol}
params.update(kwargs)
data = signedRequest("GET", "/api/v3/myTrades", params)
return data
def request(method, path, params=None):
resp = requests.request(method, ENDPOINT + path, params=params)
data = resp.json()
if "msg" in data:
logging.error(data['msg'])
return data
def signedRequest(method, path, params):
if "apiKey" not in options or "secret" not in options:
raise ValueError("Api key and secret must be set")
query = urlencode(sorted(params.items()))
query += "×tamp={}".format(int(time.time() * 1000))
secret = bytes(options["secret"].encode("utf-8"))
signature = hmac.new(secret, query.encode("utf-8"),
hashlib.sha256).hexdigest()
query += "&signature={}".format(signature)
resp = requests.request(method,
ENDPOINT + path + "?" + query,
headers={"X-MBX-APIKEY": options["apiKey"]})
data = resp.json()
if "msg" in data:
logging.error(data['msg'])
return data
def formatNumber(x):
if isinstance(x, float):
return "{:.8f}".format(x)
else:
return str(x)
感谢任何帮助或建议,谢谢
卸载,重新安装,升级。
python -m pip 卸载 python-binance
python -m pip 安装 python-binance
python -m pip install --upgrade python-binance
2. 看起来您正在编写的 binance.py 文件位于您的站点包中。 当您安装 python-binance 时,在您的站点包中创建了一个名为 binance 的文件夹
您可以移动正在处理的文件或重命名正在处理的文件。
这就是你正在做的事情:
从 binance.client 导入客户端
这就是它的意思:
从位于 site_packages 的 binance 文件夹中,从 client.py 文件中导入客户端类。
由于您有一个 binance.py,它可能会覆盖 binance 文件夹,但我不确定为什么模块会尝试导入自身。 除非你做的不同。
我将文件夹的名称从“binance”更改为“binance_mod”,这解决了这个问题。 我相信错误在于 binance 文件夹和 binance.py 文件都在站点包中。
从那里我刚刚做了
from binance_mod.client import Client
我没有问题
当您的项目中有一个名为“binance”的目录时,可能会发生这种情况。 基本上 PyCharm 会认为你是从目录而不是包本身导入的。
强烈建议不要将目录命名为binance
使用其他名称。
这是我第一次回答堆栈溢出问题。 我感到压力。
遇到了同样的问题,我花了一些时间才找到它,在新版本的 binance 中,将函数重命名为 set 而不是 Client,您可以在 binance.py 文件中检查并查看它。 当您执行set(apikey,secretkey)
时,它会使用这两个键设置一个名为选项的 var,一旦为每个函数调用完成此操作,就会使用此 var 而不是旧函数客户端(不确定旧函数是什么样的)
另一种解决方案是使用旧版本的 python binance。
============================== 编辑
所以我这样做了,一切都很好:
!pip install python-binance==0.7.5
您应该将 binance.py 重命名为 binance.client.py,至少我以这种方式解决了。 我在这里找到了解决方案: https ://github.com/sammchardy/python-binance/issues/72
我通过专门使用 conda 安装 twisted 解决了这个问题:(其他来源不起作用)
conda install twisted
我将 binance 改为 binance_mod,但它给了我这个结果: No module named 'binance.client'; 'binance' 不是一个包。
对我来说一个非常简单的修复...只要确保您的 python 代码没有保存在名为 binance.py 的文件中...
我重命名了我的,它运行顺利,似乎模块需要该文件名并且会产生一些冲突。 希望这可以帮助
安装了错误的软件包
pip3 uninstall binance
pip3 install python-binance
如果您的方向中有一个名为 binance 的文件,请将其更改为另一个名称。 它会解决你的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.