Ejemplo n.º 1
0
def GET_ACCOUNT_STATUS(LOG,out_file):

	LOG.write("GET_ACCOUNT_STATUS() " + TimeStamp() + "\n")

	try:
		client = Client(api_key, api_secret)

	except BinanceAPIException as e:
		print(e.status_code)
		print(e.message)

	try:
		data = client.get_account_status()

		# Account Info
		F1 = open(out_file,'w')
		S = "msg:            \t%s\n" % (data['msg'])
		F1.write(S)
		S = "success         \t%s\n" % (data['success'])
		F1.write(S)
		F1.close()

	except BinanceAPIException as e:
		print(e.status_code)
		print(e.message)
		LOG.write(e.message + "\n")
Ejemplo n.º 2
0
def bconnection(key,secrete):
    try:
        client =  Client(key,
                secrete)
        status = client.get_account_status()
        print(status)

        return True
    except KeyError:
        return False
Ejemplo n.º 3
0
    def __init__(self):

        apiKey = api
        secretKey = key

        if secretKey == '':
            client = Client(apiKey, '')
            print(
                "Se accedio a la cuenta sin llave secreta, no está habilitado para ejecutar trades "
            )
            habilitado = False
        else:
            try:
                client = Client(apiKey, secretKey)
                client.get_account_status()
                self.client = client
                habilitado = True
            except Exception as e:
                habilitado = False
                print(e)

        setattr(self, 'habilitado', habilitado)
        setattr(self, 'cliente', self.client)
Ejemplo n.º 4
0
class account_api(object):

	def __init__(self):
		self.client = Client("KCl8UvtnFcrlEgpqiwJlA0dr2SM3DuhKHHxiRtHA8oe7yl0JZYqas8oN2XNK0Lfz", "2wj46v8IAKpXoeigAmzfPg1VEjYi3oItNTeeNcEkDrK1HIev4nZHJr1Cd8tiJ5L0", {"verify": True, "timeout": 20})

	def get_account_info(self):
		return self.client.get_account()

	def get_account_balance(self,asset='BTC'):
		return self.client.get_asset_balance(asset=asset)

	def get_account_status(self):
		return self.client.get_account_status()

	def get_trades(self,symbol='VENETH'):
		return self.client.get_my_trades(symbol=symbol)
Ejemplo n.º 5
0
}
"""

# Get asset balance
balance = client.get_asset_balance(asset='BTC')
# Example response:
"""
{
    "asset": "BTC",
    "free": "4723846.89208129",
    "locked": "0.00000000"
}
"""

# Get account status
status = client.get_account_status()
# Example response:
"""
{
    "msg": "Order failed:Low Order fill rate! Will be reactivated after 5 minutes.",
    "success": true,
    "objs": [
        "5"
    ]
}
"""

# Getting the open orders of a symbol (after getting the account info and the balance of the traded cryptos)
orders = client.get_open_orders(symbol='BNBBTC')
## or of all the open orders:
orders = client.get_open_orders()
Ejemplo n.º 6
0
class BinanceOrders(ExchangeOrders):
    '''Handle order calls to binance.'''
    def __init__(self, config=config.binance):
        self.client = Client(config['api_key'], config['api_secret'])

    def buy_order(self, symbol, quantity, test=True):
        """
        Place a market buy order via the binance API.

        Parameters:
        ------------
        symbol: string
            A valid binance cryptocurreny symbol.

        quantity: int | float
            The amount of <symbol> to buy.

        test: boolean
            True ---> Simulate a buy via the Binance API to check authorization.

        """

        if test:
            order = self.client.create_test_order(symbol=symbol,
                                                  side=SIDE_BUY,
                                                  type=ORDER_TYPE_MARKET,
                                                  quantity=quantity)
        else:
            order = self.client.create_order(symbol=symbol,
                                             side=SIDE_BUY,
                                             type=ORDER_TYPE_MARKET,
                                             quantity=quantity)
        # return True if order else False
        return order

    def sell_order(self, symbol, quantity, test=True):
        """
        Place a market buy order via the binance API.

        Parameters:
        ------------
        symbol: string
            A valid binance cryptocurreny symbol.

        quantity: int | float
            The amount of <symbol> to buy.

        test: boolean
            True ---> Simulate a buy via the Binance API to check authorization.

        """

        if test:
            order = self.client.create_test_order(symbol=symbol,
                                                  side=SIDE_SELL,
                                                  type=ORDER_TYPE_MARKET,
                                                  quantity=quantity)
        else:
            order = self.client.create_order(symbol=symbol,
                                             side=SIDE_sell,
                                             type=ORDER_TYPE_MARKET,
                                             quantity=quantity)
        # return True if order else False
        return order

    def account_balance(self):
        """Check account balance for all cryptocurrencies."""
        return self.client.get_account()['balances']

    def coin_balance(self, symbol):
        """Check balance for a given cryptocurreny"""
        return self.client.get_asset_balance(symbol)

    def account_status(self):
        """Check for normal account status."""
        status = self.client.get_account_status()
        if status['msg'] == 'Normal' and status['success']:
            return True
        else:
            return False

    def all_orders(self, symbol):
        """Get records of all orders."""
        return self.client.get_all_orders(symbol=symbol)

    def trades(self, symbol):
        """Get records of all trades."""
        return self.client.get_my_trades(symbol=symbol)
Ejemplo n.º 7
0
from binance.client import Client
from config import *

client = Client(KEY, SECRET)

status = client.get_account_status(recvWindow=36000)
Ejemplo n.º 8
0
class Binance:
    def __init__(self):
        self.__api_key = "#########"
        self.__secret_key = "############"
        self.__client = Client(self.__api_key, self.__secret_key)
        self._info = self.exchange_info()

    def exchange_info(self):
        return self.__client.get_exchange_info()

    def deposit_credentials(self, crypto):
        credentials = self.__client.get_deposit_address(asset=crypto)
        if credentials["success"]:
            return credentials
        else:
            return self.deposit_credentials(crypto)

    def coin_info(self, coin, base="btc"):
        coin_ex = coin.upper() + base.upper()
        return self.__client.get_symbol_info(coin_ex)

    def deposit_enable(self, coin):
        s = requests.get(
            "https://www.binance.com/assetWithdraw/getAllAsset.html")
        a = json.loads(s.text)
        for each in a:
            if each["assetCode"] == coin.upper():
                return each["enableCharge"]

    def withdraw_enable(self, coin):
        s = requests.get(
            "https://www.binance.com/assetWithdraw/getAllAsset.html")
        a = json.loads(s.text)
        for each in a:
            if each["assetCode"] == coin.upper():
                return each["enableWithdraw"]

    def system_status(self):
        return self.__client.get_system_status()

    def account_info(self):
        return self.__client.get_account()

    def account_status(self):
        return self.__client.get_account_status()

    def withdraw_crypto(self,
                        crypto,
                        withdraw_amount,
                        crypto_address,
                        crypto_tag=None):
        if (crypto.lower() == "neo"):
            withdraw_amount = int(float(withdraw_amount))
        elif (crypto.lower() == "qtum"):
            withdraw_amount = int(float(withdraw_amount)) + float(
                self.withdrawal_fee(crypto))
            if withdraw_amount > float(self.balance(crypto)):
                withdraw_amount = withdraw_amount - 1
        if (crypto_tag == None):
            try:
                result = self.__client.withdraw(asset=crypto.upper(),
                                                address=crypto_address,
                                                amount=withdraw_amount)
            except BinanceAPIException as e:
                print(e)
            except BinanceWithdrawException as e:
                print(e)
                self.withdraw_crypto(crypto, withdraw_amount, crypto_address)
            else:
                print("Success")
        else:
            try:
                result = self.__client.withdraw(asset=crypto.upper(),
                                                address=crypto_address,
                                                addressTag=crypto_tag,
                                                amount=withdraw_amount)
            except BinanceAPIException as e:
                print(e)
            except BinanceWithdrawException as e:
                print(e)
                self.withdraw_crypto(crypto, withdraw_amount, crypto_address,
                                     crypto_tag)
            else:
                print("Success")

    def withdrawal_fee(self, crypto):
        return self.__client.get_withdraw_fee(asset=crypto)

    def get_balance(self, crypto):
        try:
            return self.__client.get_asset_balance(asset=crypto)
        except BinanceWithdrawException:
            self.balance(crypto)
        except BinanceAPIException:
            self.balance(crypto)

    def balance(self, crypto):
        bal = self.get_balance(crypto)
        if isinstance(bal, dict):
            return bal
        return self.balance(crypto)

    def withdraw_history(self):
        return self.__client.get_withdraw_history()

    def place_market_order(self, crypto, order_type, quantity, base="btc"):
        symbol = crypto + base
        lot_precision = self.format_specifics(crypto)[1]
        quantity = float(math.floor(float(quantity) *
                                    (10**lot_precision))) / (10**lot_precision)
        if order_type.lower() == "buy":
            order = self.__client.order_market_buy(symbol=symbol.upper(),
                                                   quantity=str(quantity))
        elif order_type.lower() == "sell":
            bal = float(self.balance(crypto)["free"])
            if quantity > bal:
                quantity = quantity - lot_precision
            order = self.__client.order_market_sell(symbol=symbol.upper(),
                                                    quantity=str(quantity))
        return order

    def format_specifics(self, crypto, base="btc"):
        for coin in self._info["symbols"]:
            if coin["symbol"] == crypto.upper() + base.upper():
                price_precision = -int(
                    math.log10(float(coin["filters"][0]["tickSize"])))
                lot_precision = -int(
                    math.log10(float(coin["filters"][1]["stepSize"])))
                return price_precision, lot_precision

    def place_limit_order(self,
                          crypto,
                          order_type,
                          quantity,
                          price,
                          base="btc"):
        symbol = crypto + base
        price_precision, lot_precision = self.format_specifics(crypto)
        if order_type.lower() == "buy":
            order = self.__client.order_limit_buy(
                symbol=symbol.upper(),
                quantity=str(
                    float(math.floor(float(quantity) * (10**lot_precision))) /
                    (10**lot_precision)),
                price=str(
                    float(math.floor(float(price) * (10**price_precision))) /
                    (10**price_precision)))
        elif order_type.lower() == "sell":
            order = self.__client.order_limit_sell(
                symbol=symbol.upper(),
                quantity=str(
                    float(math.floor(float(quantity) * (10**lot_precision))) /
                    (10**lot_precision)),
                price=str(
                    float(math.floor(float(price) * (10**price_precision))) /
                    (10**price_precision)))
        return order

    def orderbook(self, crypto, base="btc"):
        symbol = crypto + base
        try:
            return self.__client.get_order_book(symbol=symbol.upper())
        except:
            self.orderbook(crypto, base="btc")

    def buy_vol_decider(self, crypto, amount):
        cum_amount = 0
        cum_vol = 0
        for i, each in enumerate(self.orderbook(crypto)["asks"]):
            cum_amnt = cum_amount + float(each[0]) * float(each[1]) * 1.001
            cum_vol = cum_vol + float(each[1])
            if cum_amnt > amount:
                prev_amnt = cum_amnt - float(each[0]) * float(each[1]) * 1.001
                cum_vol = cum_vol - float(
                    each[1]) + (amount - prev_amnt) / (1.001 * float(each[0]))
                break
        return cum_vol

    def open_orders(self, crypto, base="btc"):
        symbol = crypto + base
        return self.__client.get_open_orders(symbol=symbol.upper())

    def cancel_order(self, crypto, order_id, base="btc"):
        symbol = crypto + base
        return self.__client.cancel_order(symbol=symbol.upper(),
                                          orderId=order_id)

    def order_status(self, crypto, order_id, base="btc"):
        symbol = crypto + base
        return self.__client.get_order(symbol=symbol.upper(), orderId=order_id)

    def place_sell_order(self, crypto):
        vol = self.balance(crypto)["free"]
        self.place_market_order(crypto, "sell", vol)

    def place_buy_order(self, crypto):
        try:
            amount = float(self.balance("btc")["free"])
            if amount > 0.001:
                vol = self.buy_vol_decider(crypto, amount)
                self.place_market_order(crypto, "buy", vol)
        except Exception as e:
            print(e)
            self.place_buy_order(crypto)
class TradingApiBinance(TradingApi):

    # override
    def __init__(self, param_pct_order_placed, stop_loss_pct):
        conf = Config()
        self.param_pct_order_placed = param_pct_order_placed
        self.API_KEY = conf.get_config('binance', 'api_key')
        self.API_SECRET = conf.get_config('binance', 'api_secret')
        self.MAX_DIFF_DATE_HOUR = int(
            conf.get_config('trading_module_params', 'max_diff_date_hour'))
        self.stop_loss_pct = stop_loss_pct
        self.client = Client(self.API_KEY,
                             self.API_SECRET)  # lib python-binance
        self.precision = int(conf.get_config('binance',
                                             'api_amount_precision'))

    # override
    def is_fake_api(self):
        return False

    # override
    def check_status_api(self):
        authorized_trading_pairs = []

        # test ping
        try:
            self.client.ping()
        except Exception as e:
            msg = "Error while trying to ping Binance API : " + str(e)
            logging.error(msg)
            slack.post_message_to_alert_error_trading(msg)
            return False, authorized_trading_pairs

        # Check system status
        try:
            status = self.client.get_system_status()
            if (status['msg'] == 'normal') and (status['status'] == 0):
                # Check account status
                status_client = self.client.get_account_status()
                if (status_client['msg']
                        == 'Normal') and (status_client['success']):
                    # Check account status related to trading
                    info_client = self.client.get_account()
                    if not info_client['canTrade']:
                        return False, authorized_trading_pairs
        except Exception as e:
            msg = "Error while trying to get system status from Binance API : " + str(
                e)
            logging.error(msg)
            slack.post_message_to_alert_error_trading(msg)
            return False, authorized_trading_pairs

        # Exchange info to verify which tradingpairs are tradable
        try:
            exchange_info = self.client.get_exchange_info()
            for symbol in exchange_info['symbols']:
                authorized_trading_pairs.append(symbol['symbol'])
        except Exception as e:
            msg = "Error while getting exchange info from binance : " + str(e)
            logging.error(msg)
            slack.post_message_to_alert_error_trading(msg)
            return False, authorized_trading_pairs

        return True, authorized_trading_pairs

    # override
    # allows to be sure that there is not to much time between predictions time and now
    def check_predictions_time_vs_server_time(self, dict_dates):
        tradable_trading_pairs = []

        # Get server time
        server_time = self.client.get_server_time()['serverTime']
        server_time_localized = localize_utc_date(server_time)

        logging.warning('server_time:' + str(server_time))
        logging.warning('server_time_localized:' + str(server_time_localized))

        for trading_pair, last_date in dict_dates.items():
            logging.warning('trading_pair diff (' + trading_pair + ')' +
                            str(server_time_localized - last_date))
            if (server_time_localized -
                    last_date) < timedelta(hours=self.MAX_DIFF_DATE_HOUR):
                tradable_trading_pairs.append(trading_pair)
            else:
                msg = 'Difference between server time (' + str(
                    server_time_localized) + ') / prediction time (' + str(
                        last_date
                    ) + ') too big for trading pair: *' + trading_pair + '*'
                logging.error(msg)
                slack.post_message_to_alert_error_trading(msg)

        return tradable_trading_pairs

    # override
    # TODO V2 : parameter = tradingpair directly
    # WARNING : can raise uncatched errors
    def get_price_ticker(self, base_asset, quote_asset, key):
        prices = self.client.get_all_tickers()
        prices_dict = {value["symbol"]: value["price"] for value in prices}
        return float(prices_dict[base_asset + quote_asset])

    # override
    # WARNING : can raise uncatched errors
    def get_buy_price(self, base_asset, quote_asset, key):
        buy_limit_price = 0
        depth = self.client.get_order_book(symbol=base_asset + quote_asset)
        if 'asks' in depth:
            ask_price = float(
                depth['asks'][0][0])  # get first ask price in order book
            buy_limit_price = ask_price + (ask_price *
                                           self.param_pct_order_placed)
        else:
            msg = 'Error while getting price for trading_pair:' + base_asset + quote_asset
            slack.post_message_to_alert_error_trading(msg)
            raise Exception(msg)
        return buy_limit_price

    # override
    def get_sell_price(self, base_asset, quote_asset, key):
        sell_limit_price = 0
        depth = self.client.get_order_book(symbol=base_asset + quote_asset)
        if 'bids' in depth:
            bid_price = float(
                depth['bids'][0][0])  # get first bid price in order book
            sell_limit_price = bid_price - (bid_price *
                                            self.param_pct_order_placed)
        else:
            msg = 'Error while getting price for trading_pair:' + base_asset + quote_asset
            slack.post_message_to_alert_error_trading(msg)
            raise Exception(msg)
        return sell_limit_price

    # override
    def get_available_amount_crypto(self, symbol):
        balance = 0
        infos_balance = self.client.get_asset_balance(asset=symbol)
        if 'free' in infos_balance:
            balance = float(infos_balance['free'])
        else:
            msg = 'Error while getting balance for symbol:' + symbol
            slack.post_message_to_alert_error_trading(msg)
            raise Exception(msg)
        return balance

    # override
    # RESULT of order:
    # {'symbol': 'VETUSDT',
    # 'orderId': 9358183,
    # 'clientOrderId': 'ILNyxOioi7cPBDGkQSKtbH',
    # 'transactTime': 1545235888618,
    # 'price': '0.00550000',
    # 'origQty': '5000.00000000',
    # 'executedQty': '0.00000000',
    # 'cummulativeQuoteQty': '0.00000000',
    # 'status': 'NEW',
    # 'timeInForce': 'GTC',
    # 'type': 'LIMIT',
    # 'side': 'SELL',
    # 'fills': []}
    def create_order(self, base_asset, quote_asset, side, quantity_from,
                     key):  # ex: USDT, ETH, 1000, BUY
        order = {}
        try:
            # TODO V2 : Use stopPrice for stop loss genre -3-4% ?
            if side == ORDER_BUY:
                limit_price = self.get_buy_price(base_asset, quote_asset, key)
                # order = self.client.order_limit_buy(
                #     symbol=base_asset + quote_asset,
                #     quantity=quantity_from,
                #     price=self.format_amount_order(limit_price))
                # TODO [SIMULATION] : To be replaced with real order + stop loss
                order = self.client.create_test_order(
                    symbol=base_asset + quote_asset,
                    side=SIDE_BUY,
                    type=ORDER_TYPE_LIMIT,
                    timeInForce=TIME_IN_FORCE_GTC,
                    quantity=quantity_from,
                    price=self.format_amount_order(limit_price))
            else:
                limit_price = self.get_sell_price(base_asset, quote_asset, key)
                # order = self.client.order_limit_sell(
                #     symbol=base_asset + quote_asset,
                #     quantity=quantity_from,
                #     price=self.format_amount_order(limit_price))
                # TODO [SIMULATION] : To be replaced with real order
                order = self.client.create_test_order(
                    symbol=base_asset + quote_asset,
                    side=SIDE_SELL,
                    type=ORDER_TYPE_LIMIT,
                    timeInForce=TIME_IN_FORCE_GTC,
                    quantity=quantity_from,
                    price=self.format_amount_order(limit_price))
            msg = 'Order placed (' + str(
                side
            ) + ') on trading_pair: ' + base_asset + quote_asset + ' - Qty: ' + str(
                quantity_from) + ' - limit: ' + str(
                    limit_price) + ' - order: ' + str(order)
            logging.warning(msg)
            slack.post_message_to_alert_actions_trading(msg)

            # Save order into DB
            dbconn = DbConnection()
            dbconn.exexute_query(TradingApiBinance.__create_query_order(order))
        except Exception as e:
            msg = "Error while creating order on tradingPair: {}, side: {}, qty:{}"
            logging.error(
                msg.format(base_asset + quote_asset, side, quantity_from))
            logging.error(str(e))
            slack.post_message_to_alert_error_trading(
                msg.format(base_asset + quote_asset, side, quantity_from) +
                '\n' + str(e))
            raise Exception(msg + str(e))

        return order['orderId']

    @staticmethod
    def __create_query_order(order):
        insertquery = 'INSERT INTO public.orders (orderId, symbol, clientOrderId, transactTime, price, origQty,' \
                      'executedQty, cummulativeQuoteQty, status, timeInForce, typeorder, side, fills)'
        insertquery += ' VALUES('
        insertquery += str(order['orderId']) + ', '
        insertquery += "'" + order['symbol'] + "', "
        insertquery += "'" + order['clientOrderId'] + "', "
        insertquery += str(order['transactTime']) + ', '
        insertquery += str(order['price']) + ', '
        insertquery += str(order['origQty']) + ', '
        insertquery += str(order['executedQty']) + ', '
        insertquery += str(order['cummulativeQuoteQty']) + ', '
        insertquery += "'" + order['status'] + "', "
        insertquery += "'" + order['timeInForce'] + "', "
        insertquery += "'" + order['type'] + "', "
        insertquery += "'" + order['side'] + "', "
        insertquery += "'" + str(order['fills']) + "')"
        return insertquery

    # override
    # {'symbol': 'VETUSDT',
    #  'origClientOrderId': 'ILNyxOioi7cPBDGkQSKtbH',
    #  'orderId': 9358183,
    #  'clientOrderId': '4ZPYz4mDfcTg6Ho0O1QhoA',
    #  'price': '0.00550000',
    #  'origQty': '5000.00000000',
    #  'executedQty': '0.00000000',
    #  'cummulativeQuoteQty': '0.00000000',
    #  'status': 'CANCELED',
    #  'timeInForce': 'GTC',
    #  'type': 'LIMIT',
    #  'side': 'SELL'}
    def get_order(self, id_order, trading_pair):
        order = self.client.get_order(symbol=trading_pair, orderId=id_order)
        return AlgOrderBinance(order)

    # override
    def get_orders(self):
        # Useless her, only for backtesting
        return 'N/A'

    # override
    def cancel_open_orders(self):
        orders = self.client.get_open_orders()
        logging.warning("Open orders to be cancelled " + str(orders))
        for order in orders:
            try:
                result = self.client.cancel_order(symbol=order['symbol'],
                                                  orderId=order['orderId'])
                msg = 'Order cancelled: ' + str(result)
                logging.warning(msg)
                slack.post_message_to_alert_actions_trading(msg)
            except Exception as e:
                msg = "Order cannot be cancelled " + str(e)
                logging.error(msg)
                slack.post_message_to_alert_error_trading(msg)

    def format_amount_order(self, amount):
        return "{:0.0{}f}".format(amount, self.precision)