Why am I getting this error 'ModuleNotFoundError: No module named 'binance.client'; 'binance' is not a package' after binance installed?

14,694

Solution 1

  1. Uninstall, Reinstall, Upgrade.

    python -m pip uninstall python-binance

    python -m pip install python-binance

    python -m pip install --upgrade python-binance

2. It looks like your binance.py file that you are writing is located in your site-packages. When you installed python-binance there was a folder created in your site-packages called binance

You could move the file you are working on or rename the file you are working on.

this is what you are doing:

from binance.client import Client

this is what it means:

from the binance folder located in site_packages import the Client Class from the client.py file.

Since you have a binance.py it could be overriding the binance folder but im not sure why a module would be trying to import itself. Unless you are doing it differently.

Solution 2

I changed the name of my folder from "binance" to "binance_mod" and this solved the issue. I believe the error is with both the binance folder and binance.py file being in site-packages.

from there I just did

from binance_mod.client import Client

and I had no issues

Solution 3

This can happen when a directory in your project called "binance". Basically PyCharm will think that you are importing from directory instead of package itself.

Highly recommended not to name directories binance use other name.

Share:
14,694
mark32
Author by

mark32

Updated on November 01, 2022

Comments

  • mark32
    mark32 over 1 year

    I am using visual studio code to try and pull candles from binance but i keep getting the following error:

    ModuleNotFoundError: No module named 'binance.client'; 'binance' is not a package
    

    heres the line of code that is causing the error:

    from binance.client import Client
    

    Ive made sure that I pip installed python-binance to the right version of python and from what ive read im guessing theres something wrong with the path but im not sure what to look for. I ran the following code check the path

    import pprint, os
    import binance
    
    pprint.pprint(os.path.abspath(binance.__file__))
    

    this was my result

    '/Users/myName/.local/lib/python3.7/site-packages/binance.py'
    

    i read that having files named binance.py could mess with it, but this was the name given when it was downloaded. if your curious about what it looks like here it is:

    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 += "&timestamp={}".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)
    

    Any help or suggestions is appreciated, Thanks!